开发者

python collections.defaultdict() compile error

开发者 https://www.devze.com 2023-03-28 19:36 出处:网络
The following code, simple and clear enough, produces an error when compiled: import string import collections

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

精彩评论

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