如何在python中检查key是否在字典中定义?
a={}
...
if 'a contains key b':
a[b] = a[b]+1
else
a[b]=1
最佳答案
使用 in
运算符:
if b in a:
演示:
>>> a = {'foo': 1, 'bar': 2}
>>> 'foo' in a
True
>>> 'spam' in a
False
您真的很想开始阅读 Python 教程 section on dictionaries涵盖了这个主题。
关于Python 检查字典中是否定义了键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19241680/