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
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 .
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With