Python defaultdict : d.get(key) vs d[key]

Today, I was trying to use Python’s defaultdict to handle a resume/experience management script that I’m building.

I noticed that  if you supply the default factory using Python defaultdict, e.g.

f = defaultdict(int)

and if you use the dict_get without providing a default value, you get a None value:

>>> f = defaultdict(int)
>>> f.get('happy')
>>> f.get('happy') + 1
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: unsupported operand type(s) for +: 'NoneType' and 'int'

but you will get the factory’s default value if you use the dict_subscript:

>>> f['happy']

then after using the dict_subscript, even when you do not provide the default value while using dict_get, you get the default value provided by the default factory:

>>> f.get('happy')

Python dictionary version  : 2.7

I am guessing that the dict_subscript updates the dictionary with the factory default value if you initialize the Python dictionary with the default_dict, but I might have to look into the dictobject.c to verify that.  This seems like a good place to start:


About Alexis Chan
This entry was posted in Uncategorized. Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s