Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to use .get() in a nested dict?

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?

like image 748
WoJ Avatar asked Jan 28 '15 08:01

WoJ


People also ask

How do you get a value from a nested dictionary?

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

Can you explain the dict get () function?

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.

How do you iterate through nested dictionaries?

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.

How do you access nested dictionary in Python?

To access element of a nested dictionary, we use indexing [] syntax in Python.


1 Answers

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
like image 139
Martijn Pieters Avatar answered Sep 23 '22 11:09

Martijn Pieters