I use .get()
to query for keys which may or may not be present in a dictionary.
In [1]: a = {'hello': True}
In [3]: print(a.get('world'))
None
I have, however, dictionaries where the key I want to check for is deeper in the structure and I do not know if the ancestors are present or not. If the dict is b = {'x': {'y': {'z': True}}}
do I have to resort to
In [5]: b.get('x') and b['x'].get('y') and b['x']['y'].get('z')
Out[5]: True
to check for 'z'
when I do not know whether 'x'
and 'y'
exist?
Access Values using get() Another way to access value(s) in a nested dictionary ( employees ) is to use the dict. get() method. This method returns the value for a specified key. If the specified key does not exist, the get() method returns None (preventing a KeyError ).
get() method is used in Python to retrieve a value from a dictionary. dict. get() returns None by default if the key you specify cannot be found. With this method, you can specify a second parameter that will return a custom default value if a key is not found.
Iterate over all values of a nested dictionary in python For a normal dictionary, we can just call the items() function of dictionary to get an iterable sequence of all key-value pairs.
To access element of a nested dictionary, we use indexing [] syntax in Python.
You can return an empty dictionary object from dict.get()
to ease chaining calls:
b.get('x', {}).get('y', {}).get('z')
but perhaps you'd be better off catching the KeyError
exception:
try:
value = b['x']['y']['z']
except KeyError:
value = None
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