Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert defaultdict to dict?

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']} 
like image 1000
user2988464 Avatar asked Dec 06 '13 16:12

user2988464


People also ask

Is Defaultdict a dict?

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.

How does Defaultdict work Defaultdict forces a dictionary?

The functionality of both dictionaries and defaultdict are almost same except for the fact that defaultdict never raises a KeyError. It provides a default value for the key that does not exists. Parameters: default_factory: A function returning the default value for the dictionary defined.

What is the difference between dict and Defaultdict?

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 . In order to provide this functionality, the Python defaultdict type does two things: It overrides .

Is Defaultdict slower than dict?

defaultdict is faster for larger data sets with more homogenous key sets (ie, how short the dict is after adding elements);


1 Answers

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.

like image 192
DSM Avatar answered Nov 01 '22 21:11

DSM