How to convert defaultdict to dict?

user2988464 picture user2988464 · Dec 6, 2013 · Viewed 60.9k times · Source

How can I convert a defaultdict

number_to_letter
defaultdict(<class 'list'>, {'2': ['a'], '3': ['b'], '1': ['b', 'a']})

to be a common dict?

{'2': ['a'], '3': ['b'], '1': ['b', 'a']}

Answer

DSM picture DSM · Dec 6, 2013

You can simply call dict:

>>> a
defaultdict(<type 'list'>, {'1': ['b', 'a'], '3': ['b'], '2': ['a']})
>>> dict(a)
{'1': ['b', 'a'], '3': ['b'], '2': ['a']}

but remember that a defaultdict is a dict:

>>> isinstance(a, dict)
True

just with slightly different behaviour, in that when you try access a key which is missing -- which would ordinarily raise a KeyError -- the default_factory is called instead:

>>> a.default_factory
<type 'list'>

That's what you see when you print a before the data side of the dictionary appears.

So another trick to get more dictlike behaviour back without actually making a new object is to reset default_factory:

>>> a.default_factory = None
>>> a[4].append(10)
Traceback (most recent call last):
  File "<ipython-input-6-0721ca19bee1>", line 1, in <module>
    a[4].append(10)
KeyError: 4

but most of the time this isn't worth the trouble.