Search the Python dictionary with a nested dictionary with default values

>>> d2
{'egg': 3, 'ham': {'grill': 4, 'fry': 6, 'bake': 5}, 'spam': 2}
>>> d2.get('spamx',99)
99
>>> d2.get('ham')['fry']
6

I want to get the fry value inside the ham, if not, get the value 99 or 88 as a second example. But how?

+5
source share
4 answers
d2.get('ham', {}).get('fry', 88)

I would probably divide it into several statements in real life.

ham = d2.get('ham', {})
fry = ham.get('fry', 88)
+13
source

For default values, the first default value must be a dictionary for the correct operation, so that you can correctly encode .get calls if the first one fails.

d.get('ham',{}).get('fry',88)

you can also use try except block

def get_ham_fry()
  try:
    return d['ham']['fry']
  except AttributeError,e:
    return 88
+3
source

,

def get_nested(d, list_of_keys, default):
    for k in list_of_keys:
        if k not in d: 
            return default
        d=d[k]
    return d

print get_nested(d2,['ham','spam'],99)
print get_nested(d2,['ham','grill'],99)
+3

:

def get(root, *keys):
    """
    Returns root[k_1][k_2]...[k_n] if all k_1, ..., k_n are valid keys/indices. 
    Returns None otherwise
    """
    if not keys:
        return root
    if keys[0] not in root:
        return None
    if keys[0] in root:
        return get(root[keys[0]], *keys[1:])

:

>>> d = {'a': 1, 'b': {'c': 3}}
>>> get(d, 'b', 'c')
3
>>> get(d. 'key that not in d')
None
>>> get(d)
{'a': 1, 'b': {'c': 3}}
0

All Articles