开发者

python collections.defaultdict() compile error

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


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:
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜