Python check that key is defined in dictionary

Question:

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
Asked By: user10756

||

Answers:

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.

Answered By: Martijn Pieters

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.

Answered By: bruno desthuilliers
if b in a:
     a[b]+=1
else:
    a[b]=1
Answered By: Ishaan
a = {'foo': 1, 'bar': 2}
if a.has_key('foo'):
    a['foo']+=1
else:
    a['foo']=1
parsedData=[]
dataRow={}
if not any(d['url'] == dataRow['url'] for d in self.parsedData):
       self.parsedData.append(dataRow)
Answered By: Ranvijay Sachan
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.