Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.0k views
in Technique[技术] by (71.8m points)

python - defaultdict : first argument must be callable or None

I ran the following code :

from collections import defaultdict
lst = list(range(0,5))
d = defaultdict(lst)

and I got this error :

TypeError: first argument must be callable or None

Please help

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

For a defaultdict the default value is usually not really a value, it a factory: a method that generates a new value. You can solve this issue by using a lambda expression that generates a list:

lst = lambda:list(range(0,5))
d = defaultdict(lst)

This is also a good idea here, since otherwise all default values would reference the same list. For instance here:

d[1].append(14)

will not have impact on d[2] (given both d[1] and d[2] did not exist).

You can however achieve this with:

val = list(range(0,5))
lst = lambda:val
d = defaultdict(lst)

But this can have unwanted side effects: if you here perform d[1].append(14) then d[2] will be [1,2,3,4,5,14] and d[1] is d[2] will be True:

$ python3
Python 3.5.2 (default, Nov 17 2016, 17:05:23) 
[GCC 5.4.0 20160609] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> from collections import defaultdict
>>> val = list(range(0,5))
>>> lst = lambda:val
>>> d = defaultdict(lst)
>>> d[1]
[0, 1, 2, 3, 4]
>>> d[1].append(14)
>>> d[2]
[0, 1, 2, 3, 4, 14]
>>> d[1] is d[2]
True

whereas:

$ python3
Python 3.5.2 (default, Nov 17 2016, 17:05:23) 
[GCC 5.4.0 20160609] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> from collections import defaultdict
>>> lst = lambda:list(range(0,5))
>>> d = defaultdict(lst)
>>> d[1]
[0, 1, 2, 3, 4]
>>> d[1].append(14)
>>> d[2]
[0, 1, 2, 3, 4]
>>> d[1] is d[2]
False

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...