python collections.defaultdict() compile error

荒凉一梦 提交于 2019-12-13 14:04:31

问题


The following code, simple and clear enough, produces an error when compiled:

import string
import collections

#create dictionary with alphabets as keys, and empty values
list = ['aema', 'airplane', 'amend']

gen_dict = dict.fromkeys(string.ascii_lowercase, '')

gen_dict = collections.defaultdict(list)

for x in list:
    gen_dict['a'].append(x)

and the error produced is:

Traceback (most recent call last):
  File "indexdict.py", line 14, in <module>
    gen_dict = collections.defaultdict(list)
TypeError: first argument must be callable

any idea? thanks in advance


回答1:


you overwrite the internal list, being the name of a type, with your list = ['aema', 'airplane', 'amend'] above. Rename your list to e.g. keys or keylist and all will be fine.

So replace

list = ['aema', 'airplane', 'amend']

with

keys = ['aema', 'airplane', 'amend']

and

for x in list:

with

for x in keys:


来源:https://stackoverflow.com/questions/7070296/python-collections-defaultdict-compile-error

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