Lin Ma Lin Ma - 1 year ago 227
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

Answer Source

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')
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download