[英]How to set default value to all keys of a dict object in python?
I know you can use setdefault(key, value) to set default value for a given key, but is there a way to set default values of all keys to some value after creating a dict ? 我知道你可以使用setdefault(key,value)来设置给定键的默认值,但有没有办法在创建dict后将所有键的默认值设置为某个值?
Put it another way, I want the dict to return the specified default value for every key I didn't yet set. 换句话说,我希望dict为我尚未设置的每个键返回指定的默认值。
You can replace your old dictionary with a defaultdict
: 您可以使用
defaultdict
替换旧字典:
>>> from collections import defaultdict
>>> d = {'foo': 123, 'bar': 456}
>>> d['baz']
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
KeyError: 'baz'
>>> d = defaultdict(lambda: -1, d)
>>> d['baz']
-1
The "trick" here is that a defaultdict
can be initialized with another dict
. 这里的“技巧”是可以用另一个
dict
初始化defaultdict
。 This means that you preserve the existing values in your normal dict
: 这意味着您保留普通
dict
的现有值:
>>> d['foo']
123
Use defaultdict 使用defaultdict
from collections import defaultdict
a = {}
a = defaultdict(lambda:0,a)
a["anything"] # => 0
This is very useful for case like this,where default values for every key is set as 0: 这对于这样的情况非常有用,其中每个键的默认值设置为0:
results ={ 'pre-access' : {'count': 4, 'pass_count': 2},'no-access' : {'count': 55, 'pass_count': 19}
for k,v in results.iteritems():
a['count'] += v['count']
a['pass_count'] += v['pass_count']
In case you actually mean what you seem to ask, I'll provide this alternative answer. 如果你真的是指你似乎问的问题,我会提供这个替代答案。
You say you want the dict to return a specified value, you do not say you want to set that value at the same time, like defaultdict
does. 你说你希望dict 返回一个指定的值,你不是说你想同时设置那个值,就像
defaultdict
一样。 This will do so: 这样做:
class DictWithDefault(dict):
def __init__(self, default, **kwargs):
self.default = default
super(DictWithDefault, self).__init__(**kwargs)
def __getitem__(self, key):
if key in self:
return super(DictWithDefault, self).__getitem__(key)
return self.default
Use like this: 使用这样:
d = DictWIthDefault(99, x=5, y=3)
print d["x"] # 5
print d[42] # 99
42 in d # False
d[42] = 3
42 in d # True
Alternatively, you can use a standard dict
like this: 或者,您可以使用这样的标准
dict
:
d = {3: 9, 4: 2}
default = 99
print d.get(3, default) # 9
print d.get(42, default) # 99
Is this what you want: 这是你想要的吗:
>>> d={'a':1,'b':2,'c':3}
>>> default_val=99
>>> for k in d:
... d[k]=default_val
...
>>> d
{'a': 99, 'b': 99, 'c': 99}
>>>
>>> d={'a':1,'b':2,'c':3}
>>> from collections import defaultdict
>>> d=defaultdict(lambda:99,d)
>>> d
defaultdict(<function <lambda> at 0x03D21630>, {'a': 1, 'c': 3, 'b': 2})
>>> d[3]
99
You can use the following class. 您可以使用以下课程。 Just change zero to any default value you like.
只需将零更改为您喜欢的任何默认值。 The solution was tested in Python 2.7.
该解决方案在Python 2.7中进行了测试。
class cDefaultDict(dict):
# dictionary that returns zero for missing keys
# keys with zero values are not stored
def __missing__(self,key):
return 0
def __setitem__(self, key, value):
if value==0:
if key in self: # returns zero anyway, so no need to store it
del self[key]
else:
dict.__setitem__(self, key, value)
Not after creating it, no. 不是在创建它之后,没有。 But you could use a
defaultdict
in the first place, which sets default values when you initialize it. 但您可以首先使用
defaultdict
,它在初始化时设置默认值。
defaultdict
can do something like that for you. defaultdict
可以为你做类似的事情。
Example: 例:
>>> from collections import defaultdict
>>> d = defaultdict(list)
>>> d
defaultdict(<class 'list'>, {})
>>> d['new'].append(10)
>>> d
defaultdict(<class 'list'>, {'new': [10]})
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.