Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python nested dictionary lookup 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 value of fry inside of ham, if not, get value, 99 or 88 as the 2nd example. But how?

like image 545
litd Avatar asked Aug 09 '10 06:08

litd


People also ask

How do you get a specific value from a nested dictionary in Python?

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

How does Python handle nested dictionary?

Addition of elements to a nested Dictionary can be done in multiple ways. One way to add a dictionary in the Nested dictionary is to add values one be one, Nested_dict[dict][key] = 'value'. Another way is to add the whole dictionary in one go, Nested_dict[dict] = { 'key': 'value'}.

What is the difference between Defaultdict and dict?

The main difference between defaultdict and dict is that when you try to access or modify a key that's not present in the dictionary, a default value is automatically given to that key . In order to provide this functionality, the Python defaultdict type does two things: It overrides .

How do you create an empty nested dictionary in Python?

In Python, we can create an empty dictionary by putting no elements inside curly brackets.


4 Answers

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

I would probably break it down into several statements in real life.

ham = d2.get('ham', {})
fry = ham.get('fry', 88)
like image 85
Oddthinking Avatar answered Sep 23 '22 10:09

Oddthinking


If you need to do this a lot, you can write a helper function

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)
like image 44
John La Rooy Avatar answered Sep 23 '22 10:09

John La Rooy


For the default values of get to work correctly the first default needs to be a dictionary, so that you can chain the .get calls correctly if the first fails.

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

you could also use a try, except block

def get_ham_fry()
  try:
    return d['ham']['fry']
  except AttributeError,e:
    return 88
like image 44
Michael Anderson Avatar answered Sep 24 '22 10:09

Michael Anderson


Here's a solution for dealing with nested dictionaries:

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:])

Usage:

>>> d = {'a': 1, 'b': {'c': 3}}
>>> get(d, 'b', 'c')
3
>>> get(d. 'key that's not in d')
None
>>> get(d)
{'a': 1, 'b': {'c': 3}}
like image 38
Michael Avatar answered Sep 23 '22 10:09

Michael