2013-10-08 50 views

回答

78

使用in操作:

if b in a: 

演示:

>>> a = {'foo': 1, 'bar': 2} 
>>> 'foo' in a 
True 
>>> 'spam' in a 
False 

你真的要开始阅读Python的教程中,section on dictionaries涵盖这个主题。

7

它的语法是if key in dict:

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

现在你可能会想看看collections.defaultdict和(针对上述案例)collections.Counter

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

这不能在Python 3中使用,最好使用'in' –

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