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.
Code
import collections
a = collections.defaultdict("")
a[1]="Hello"
a[2]="World"
print a
Error Message
a = collections.defaultdict("")
TypeError: first argument must be callable
When the int class is passed as the default_factory argument, then a defaultdict is created with default value as zero.
The defaultdict is a subdivision of the dict class. Its importance lies in the fact that it allows each new key to be given a default value based on the type of dictionary being created. A defaultdict can be created by giving its declaration an argument that can have three values; list, set or int.
So, you can say that defaultdict is much like an ordinary dictionary. The main difference between defaultdict and dict is that when you try to access or modify a key that's not present in the dictionary, a default value is automatically given to that key .
A defaultdict works exactly like a normal dict, but it is initialized with a function (“default factory”) that takes no arguments and provides the default value for a nonexistent key. A defaultdict will never raise a KeyError. Any key that does not exist gets the value returned by the default factory.
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')
It's right. You have an instance of a string instead of something that returns a string. What you want is collections.defaultdict(str)
. That is because str()
returns ""
. You could have found out what the type was like this:
>>> type("")
<class 'str'>
Therefore, if you didn't know the name of the class, you could have done this:
a = collections.defaultdict(type(""))
or
a = collections.defaultdict("".__class__)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With