Get nested value

Python, Dictionary, List · Oct 28, 2020

Retrieves the value of the nested key indicated by the given selector list from a dictionary or list.

  • Use functools.reduce() to iterate over the selectors list.
  • Apply operator.getitem() for each key in selectors, retrieving the value to be used as the iteratee for the next iteration.
from functools import reduce
from operator import getitem

def get(d, selectors):
  return reduce(getitem, selectors, d)
users = {
  'freddy': {
    'name': {
      'first': 'fred',
      'last': 'smith'
    },
    'postIds': [1, 2, 3]
  }
}
get(users, ['freddy', 'name', 'last']) # 'smith'
get(users, ['freddy', 'postIds', 1]) # 2

More like this

  • Python Lists

    A snippet collection of list helpers and tips for Python 3.6.

    Collection · 100 snippets

  • Combine dictionary values

    Combines two or more dictionaries, creating a list of values for each key.

    Python, Dictionary · Apr 4, 2021

  • Find keys with value

    Finds all keys in the provided dictionary that have the given value.

    Python, Dictionary · Nov 2, 2020

  • Find key of value

    Finds the first key in the provided dictionary that has the given value.

    Python, Dictionary · Nov 2, 2020