Skip to content


Get nested value

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

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

Start typing a keyphrase to see matching snippets.