我想在更新密钥的值之前测试字典中是否存在密钥。 我写了以下代码:
if 'key1' in dict.keys():
print "blah"
else:
print "boo"
我认为这不是完成这项任务的最佳方式。有没有更好的方法来测试字典中的密钥?
我想在更新密钥的值之前测试字典中是否存在密钥。 我写了以下代码:
if 'key1' in dict.keys():
print "blah"
else:
print "boo"
我认为这不是完成这项任务的最佳方式。有没有更好的方法来测试字典中的密钥?
in
是测试a中密钥是否存在的预期方法 dict
。
d = dict()
for i in xrange(100):
key = i % 10
if key in d:
d[key] += 1
else:
d[key] = 1
如果您想要默认值,可以随时使用 dict.get()
:
d = dict()
for i in xrange(100):
key = i % 10
d[key] = d.get(key, 0) + 1
...并且如果您想要始终确保您可以使用的任何键的默认值 defaultdict
来自 collections
模块,像这样:
from collections import defaultdict
d = defaultdict(lambda: 0)
for i in xrange(100):
d[i % 10] += 1
......但总的来说, in
关键字是最好的方法。
您可以使用。来测试字典中是否存在密钥 在 关键词:
d = {'a': 1, 'b': 2}
'a' in d # <== evaluates to True
'c' in d # <== evaluates to False
在变更之前检查字典中是否存在键的常见用法是默认初始化值(例如,如果您的值是列表,并且您希望确保有一个空列表,您可以将其追加到插入键的第一个值时)。在这种情况下,你可能会发现 collections.defaultdict()
类型是有趣的。
在旧代码中,您可能还会发现一些用途 has_key()
,一种用于检查字典中键存在的已弃用方法(只需使用 key_name in dict_name
,而是)。
你可以缩短这个:
if 'key1' in dict:
...
然而,这充其量只是一种美容改善。为什么你认为这不是最好的方法?
我建议使用 setdefault
方法而不是。听起来它会做你想要的一切。
>>> d = {'foo':'bar'}
>>> q = d.setdefault('foo','baz') #Do not override the existing key
>>> print q #The value takes what was originally in the dictionary
bar
>>> print d
{'foo': 'bar'}
>>> r = d.setdefault('baz',18) #baz was never in the dictionary
>>> print r #Now r has the value supplied above
18
>>> print d #The dictionary's been updated
{'foo': 'bar', 'baz': 18}
有关接受答案的建议方法(10米循环)的速度执行的其他信息:
'key' in mydict
经过时间1.07秒mydict.get('key')
经过时间1.84秒mydefaultdict['key']
经过时间1.07秒因此使用 in
要么 defaultdict
建议反对 get
。
python中的字典有一个get('key',default)方法。所以你可以设置一个默认值,以防没有密钥。
values = {...}
myValue = values.get('Key', None)
如需检查,您可以使用 has_key()
方法
if dict.has_key('key1'):
print "it is there"
如果你想要一个值,那么你可以使用 get()
方法
a = dict.get('key1', expeced_type)
如果要将元组或列表或字典或任何字符串作为默认值作为返回值,请使用 get()
方法
a = dict.get('key1', {}).get('key2', [])
使用三元运算符:
message = "blah" if 'key1' in dict else "booh"
print(message)