我想在更新键的值之前测试字典中是否存在键。我编写了以下代码:
if 'key1' in dict.keys():
print "blah"
else:
print "boo"
我认为这不是完成这项任务的最佳方式。有没有更好的方法来测试字典中的关键字?
我想在更新键的值之前测试字典中是否存在键。我编写了以下代码:
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中是否存在成员
有关已接受答案的建议方法(1000万个循环)执行速度的其他信息:
mydict中的“key”已用时间1.07秒mydict.get('key')运行时间1.84秒mydefaultdict['key']已用时间1.07秒
因此,建议对get使用in或defaultdict。
您可以使用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')
仅Python 2:(Python 2.7已经支持“in”)
可以使用has_key()方法:
if dict.has_key('xyz')==1:
# Update the value for the key
else:
pass
使用Python三元运算符:
message = "blah" if 'key1' in my_dict else "booh"
print(message)