Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python defaultdict with string as type of value

Tags:

python

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
like image 297
Lin Ma Avatar asked Apr 29 '16 23:04

Lin Ma


People also ask

What is the default value in Defaultdict?

When the int class is passed as the default_factory argument, then a defaultdict is created with default value as zero.

What is Defaultdict int in Python?

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.

What is the difference between dict and Defaultdict?

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 .

What does the Defaultdict () function do?

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.


2 Answers

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')
like image 87
TigerhawkT3 Avatar answered Oct 10 '22 09:10

TigerhawkT3


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__)
like image 35
zondo Avatar answered Oct 10 '22 10:10

zondo