Lin Ma Lin Ma - 11 months ago 129
Python Question

Python defaultdict with string as type of value

Need to create a defaultdict, value type is normal Python string, it seems my below method does not work? Post compile error message. Using Python 2.7 and wondering any good ideas how to fix? Thanks.


import collections

a = collections.defaultdict("")


print a

Error Message

a = collections.defaultdict("")
TypeError: first argument must be callable


As the error says, the first argument has to be a callable that produces the value you want. Use str:

a = collections.defaultdict(str)

If necessary, you can create a wrapper with a lambda function:

a = collections.defaultdict(lambda: 'initial')