Created
February 23, 2022 14:45
-
-
Save entirelymagic/3c43cddd056fa2d18070697df4845cf1 to your computer and use it in GitHub Desktop.
Get from a dictionary the value using selectors
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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