[ACCEPTED]-One liner to look up nested value from a dictionary python-functools

Accepted answer
Score: 11

You can use functools.reduce():

from functools import reduce # In Python 2, don't import it. (It's a built-in)

print(reduce(dict.get, keys, d))

# 'a'

For the keys you mentioned, it 5 goes like this:

  • call dict.get with d (initial) and the first item of keys (11) to get d[11]
  • call dict.get with the result (a dictionary) and the next item in keys (21) to get {...}[21]
  • call dict.get ...
    ...

until keys is "reduced" to 4 the final value ('a')

Edit: As dict.get results in None if there 3 is no such key, there might be undesired 2 results. If you want to have a KeyError, you can 1 use operator.getitem instead.

Score: 0

Here's a solution I came up with that also 5 gives back useful information when given 4 an invalid lookup path, and allows you to 3 dig through arbitrary json, including nested 2 list and dict structures. (Sorry it's not 1 a one-liner).

def get_furthest(s, path):
    '''
    Gets the furthest value along a given key path in a subscriptable structure.

    subscriptable, list -> any
    :param s: the subscriptable structure to examine
    :param path: the lookup path to follow
    :return: a tuple of the value at the furthest valid key, and whether the full path is valid
    '''

    def step_key(acc, key):
        s = acc[0]
        if isinstance(s, str):
            return (s, False)
        try:
            return (s[key], acc[1])
        except LookupError:
            return (s, False)

    return reduce(step_key, path, (s, True))

More Related questions