我想在更新键的值之前测试字典中是否存在键。我编写了以下代码:

if 'key1' in dict.keys():
  print "blah"
else:
  print "boo"

我认为这不是完成这项任务的最佳方式。有没有更好的方法来测试字典中的关键字?


当前回答

您可以使用for循环来遍历字典,并获得要在字典中查找的键的名称。之后,检查是否存在或不使用if条件:

dic = {'first' : 12, 'second' : 123}
for each in dic:
    if each == 'second':
        print('the key exists and the corresponding value can be updated in the dictionary')

其他回答

使用EAFP(请求宽恕比允许更容易):

try:
   blah = dict["mykey"]
   # key exists in dict
except KeyError:
   # key doesn't exist in dict

请参阅其他堆栈溢出帖子:

在Python中使用“try”与“if”检查Python中是否存在成员

我建议改用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}

Python中的字典有一个get('key',默认)方法。因此,您可以设置一个默认值,以防没有任何键。

values = {...}
myValue = values.get('Key', None)

使用Python三元运算符:

message = "blah" if 'key1' in my_dict else "booh"
print(message)

您可以使用in关键字测试字典中是否存在关键字:

d = {'a': 1, 'b': 2}
'a' in d # <== evaluates to True
'c' in d # <== evaluates to False

在对字典中的键进行变异之前,检查其是否存在的一个常见用法是默认初始化该值(例如,如果您的值是列表,并且您希望确保在插入键的第一个值时有一个空列表可以附加到该空列表中)。在这种情况下,您可能会发现collections.defaultdict()类型很有趣。

在旧代码中,您可能还会发现has_key()的一些用法,这是一种不推荐使用的检查字典中是否存在键的方法(只需在dict_name中使用key_name即可)。