Is there a single line method to check whether a Python 2d dict has an inner key/value?
Right now i do somethng like this:
if d.has_key(k1):
if d[k1].has_key(k2):
# do something
Is there a better way to do this?
Thanks
Check If Key Exists using has_key() method Using has_key() method returns true if a given key is available in the dictionary, otherwise, it returns a false. With the Inbuilt method has_key(), use the if statement to check if the key is present in the dictionary or not.
Use get() and Key to Check if Value Exists in a Dictionary Dictionaries in Python have a built-in function key() , which returns the value of the given key. At the same time, it would return None if it doesn't exist.
To access element of a nested dictionary, we use indexing [] syntax in Python.
values() to check if a value is in a dictionary. Use dict. values() to get the values of a dictionary. Use the expression value in dictionary_values to return True if the value is in the dictionary and False if otherwise.
if k2 in d.get(k1, {}):
# do something
The above fragment is nice if you don't care about whether k1 actually exists or not and merely want to know whether k2 exists inside of it if it does exist. As you can see from my code snippet, I prefer the in
operator, but you could just as easily say
if d.get(k1, {}).has_key(k2):
# do something
if you prefer that idiom, but the has_key
method has been deprecated in Python 3.x, so you should probably avoid it.
You can use in
:
if k1 in d and k2 in d[k1]:
The has_key
method is deprecated and is removed in Python 3.x.
Related:
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