Skip to content

Instantly share code, notes, and snippets.

@entirelymagic
Created February 23, 2022 14:45
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save entirelymagic/3c43cddd056fa2d18070697df4845cf1 to your computer and use it in GitHub Desktop.
Save entirelymagic/3c43cddd056fa2d18070697df4845cf1 to your computer and use it in GitHub Desktop.
Get from a dictionary the value using selectors
from functools import reduce
from operator import getitem
def get_from_dict(d, selectors):
"""
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.
users = {
'freddy': {
'name': {
'first': 'fred',
'last': 'smith'
},
'postIds': [1, 2, 3]
}
}
get(users, ['freddy', 'name', 'last']) # 'smith'
get(users, ['freddy', 'postIds', 1]) # 2
"""
return reduce(getitem, selectors, d)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment