37

How to check that the key is defined in dictionary in python?

a={}
...
if 'a contains key b':
  a[b] = a[b]+1
else
  a[b]=1
Eric Leschinski
  • 146,994
  • 96
  • 417
  • 335
user10756
  • 643
  • 1
  • 6
  • 12

5 Answers5

88

Use the in operator:

if b in a:

Demo:

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

You really want to start reading the Python tutorial, the section on dictionaries covers this very subject.

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
8

Its syntax is if key in dict: :

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

Now you may want to look at collections.defaultdict and (for the above case) collections.Counter.

Fengyang Wang
  • 11,901
  • 2
  • 38
  • 67
bruno desthuilliers
  • 75,974
  • 6
  • 88
  • 118
2
a = {'foo': 1, 'bar': 2}
if a.has_key('foo'):
    a['foo']+=1
else:
    a['foo']=1
1
if b in a:
     a[b]+=1
else:
    a[b]=1
Ishaan
  • 886
  • 6
  • 12
1
parsedData=[]
dataRow={}
if not any(d['url'] == dataRow['url'] for d in self.parsedData):
       self.parsedData.append(dataRow)
Ranvijay Sachan
  • 2,407
  • 3
  • 30
  • 49