问题:
I wanted to test if a key exists in a dictionary before updating the value for the key. 我想在更新密钥值之前测试字典中是否存在密钥。 I wrote the following code: 我写了以下代码:
if 'key1' in dict.keys():
print "blah"
else:
print "boo"
I think this is not the best way to accomplish this task. 我认为这不是完成此任务的最佳方法。 Is there a better way to test for a key in the dictionary? 有没有更好的方法来测试字典中的键?
解决方案:
参考一: https://stackoom.com/question/6izm/检查字典中是否已存在给定键参考二: https://oldbug.net/q/6izm/Check-if-a-given-key-already-exists-in-a-dictionary
来源:oschina
链接:https://my.oschina.net/u/4438370/blog/4296399