Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if a key-value pair is present in a dictionary?

Is there a smart pythonic way to check if there is an item (key,value) in a dict?

a={'a':1,'b':2,'c':3} b={'a':1} c={'a':2}  b in a: --> True c in a: --> False 
like image 228
Peter Avatar asked Dec 14 '15 17:12

Peter


People also ask

How do you check if a dictionary already contains a key?

You can check if a key exists in a dictionary using the keys() method and IN operator. The keys() method will return a list of keys available in the dictionary and IF , IN statement will check if the passed key is available in the list. If the key exists, it returns True else, it returns False .

How do you check if a key value pair exists in a dictionary C#?

Syntax: public bool ContainsKey (TKey key); Here, the key is the Key which is to be located in the Dictionary. Return Value: This method will return true if the Dictionary contains an element with the specified key otherwise, it returns false.


1 Answers

Use the short circuiting property of and. In this way if the left hand is false, then you will not get a KeyError while checking for the value.

>>> a={'a':1,'b':2,'c':3} >>> key,value = 'c',3                # Key and value present >>> key in a and value == a[key] True >>> key,value = 'b',3                # value absent >>> key in a and value == a[key] False >>> key,value = 'z',3                # Key absent >>> key in a and value == a[key] False 
like image 174
Bhargav Rao Avatar answered Oct 11 '22 15:10

Bhargav Rao