Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python check that key is defined in dictionary [duplicate]

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 
like image 224
user10756 Avatar asked Oct 08 '13 07:10

user10756


People also ask

Can KEY be repeated in dictionary Python?

Python dictionary doesn't allow key to be repeated.

How do you check if two dictionaries have the same keys and values?

Check if two nested dictionaries are equal in Python To do this task, we are going to use the == operator and this method will help the user to check whether the two given dictionaries are equal or not.


2 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.

like image 108
Martijn Pieters Avatar answered Oct 08 '22 20:10

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.

like image 27
bruno desthuilliers Avatar answered Oct 08 '22 21:10

bruno desthuilliers