Python检查字典中是否定义了键

37

如何在Python中检查字典中是否定义了特定的键?

a={}
...
if 'a contains key b':
  a[b] = a[b]+1
else
  a[b]=1
5个回答

88

使用 in 运算符:

if b in a:

演示:

>>> a = {'foo': 1, 'bar': 2}
>>> 'foo' in a
True
>>> 'spam' in a
False
你真的想开始阅读Python教程,其中字典部分详细介绍了这个主题。

8

它的语法是if key in dict:

if "b" in a:
    a["b"] += 1
else:
    a["b"] = 1

现在你可能想看看collections.defaultdict和(对于上述情况)collections.Counter

2
a = {'foo': 1, 'bar': 2}
if a.has_key('foo'):
    a['foo']+=1
else:
    a['foo']=1

4
不能在Python 3中使用,最好使用in - Connor Wyatt

1
parsedData=[]
dataRow={}
if not any(d['url'] == dataRow['url'] for d in self.parsedData):
       self.parsedData.append(dataRow)

1
if b in a:
     a[b]+=1
else:
    a[b]=1

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接