从defaultdict获取原始密钥集

时间:2017-07-30 09:11:36

标签: python defaultdict

有没有办法从defaultdict获取原始/一致的密钥列表,即使请求了非现有密钥?

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']

3 个答案:

答案 0 :(得分:9)

你必须排除。具有默认值的键!

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

与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

答案 1 :(得分:0)

[key for key in d.keys() if key != 'default']

答案 2 :(得分:0)

default_factory()是可调用的,不需要每次都返回相同的值!

>>> from collections import defaultdict
>>> from random import random
>>> d = defaultdict(lambda: random())
>>> d[1]
0.7411252345322932
>>> d[2]
0.09672701444816645
>>> d.keys()
dict_keys([1, 2])
>>> d.default_factory()
0.06277993247659297
>>> d.default_factory()
0.4388136209046052
>>> d.keys()
dict_keys([1, 2])
>>> [k for k in d.keys() if d[k] != d.default_factory()]
[1, 2]