Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

get original key set from defaultdict

Is there a way to get the original/consistent list of keys from defaultdict even when non existing keys were requested?

from collections import defaultdict
>>> d = defaultdict(lambda: 'default', {'key1': 'value1', 'key2' :'value2'})
>>>
>>> d.keys()
['key2', 'key1']
>>> d['bla']
'default'
>>> d.keys() # how to get the same: ['key2', 'key1']
['key2', 'key1', 'bla']
like image 609
Vitali Bichov Avatar asked Jul 30 '17 09:07

Vitali Bichov


People also ask

What does Defaultdict return?

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.

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 set in Python?

The Python defaultdict type behaves almost exactly like a regular Python dictionary, but if you try to access or modify a missing key, then defaultdict will automatically create the key and generate a default value for it. This makes defaultdict a valuable option for handling missing keys in dictionaries.

Is Defaultdict faster than dict?

get method and the experiment shows that defaultdict more that two times faster than dict. get method.


1 Answers

You have to exclude. the keys that has the default value!

>>> [i for i in d if d[i]!=d.default_factory()]
['key2', 'key1']

Time comparison with method suggested by Jean,

>>> def funct(a=None,b=None,c=None):
...     s=time.time()
...     eval(a)
...     print time.time()-s
...
>>> funct("[i for i in d if d[i]!=d.default_factory()]")
9.29832458496e-05
>>> funct("[k for k,v in d.items() if v!=d.default_factory()]")
0.000100135803223
>>> ###storing the default value to a variable and using the same in the list comprehension reduces the time to a certain extent!
>>> defa=d.default_factory()
>>> funct("[i for i in d if d[i]!=defa]")
8.82148742676e-05
>>> funct("[k for k,v in d.items() if v!=defa]")
9.79900360107e-05
like image 166
Keerthana Prabhakaran Avatar answered Sep 28 '22 20:09

Keerthana Prabhakaran