TypeError: first argument must be callable, defaultdict

时光毁灭记忆、已成空白 提交于 2019-12-02 06:13:05

Such a nested dict structure can be achieved using a recursive defaultdict "tree":

def tree(): 
    return defaultdict(tree)

publishDB = tree()

At each level, the defaultdicts are instantiated with tree which is a zero-argument callable, as required. Then you can simply assign marks:

publishDB[subject][student][assignment] = mark

defaultdict() requires that its first argument be callable: it must be a class that you want an instance of, or a function that returns an instance.

defaultdict({}) has an empty dictionary, which is not callable.

You likely want defaultdict(dict), as dict is a class that returns a dictionary when instantiated (called).

But that still doesn't solve the problem... just moves it to a different level. The outer defaultdict(...) in defaultdict(defaultdict(dict)) has the exact same issue because defaultdict(dict) isn't callable.

You can use a lambda expression to solve this, creating a one-line function that, when called, creates a defaultdict(dict):

 defaultdict(lambda: defaultdict(dict))

You could also use the lambda at the lower level if you wanted:

defaultdict(lambda: defaultdict(lambda: {}))
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!