Last active
July 29, 2021 18:37
-
-
Save pcn/a3a2031a15c3243dedd4c5afda98cfd7 to your computer and use it in GitHub Desktop.
Assoc-in and get-in for python
This file contains 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
# XXX maybe move this to the util module | |
# Let's make our lives easier with assoc-in and get-in | |
# From: https://stackoverflow.com/questions/10578554/equivalent-of-clojures-assoc-in-and-get-in-in-python | |
# with additional support for deferencing an array | |
def _assoc_in(dct, path, value, sep=':'): | |
"""In a dictionary dct, using the path (which is a | |
<sep>-separated string) assign the resulting key to value, | |
overwriting it if its present. If it encounters an iterable and the current | |
path component is an integer, operates on that. | |
""" | |
for x in path.split(sep): | |
if x.isdigit(): | |
if isinstance(dct, list): | |
prev, dct = dct, dct[int(x)] | |
else: | |
prev, dct = dct, dct.setdefault(x, {}) | |
else: | |
prev, dct = dct, dct.setdefault(x, {}) | |
prev[x] = value | |
def _get_in(dct, path, sep=':'): | |
"""In a dictionary dct, using the path (which is a | |
<sep>-separated string) get the resulting key's value""" | |
for x in path.split(sep): | |
if x.isdigit(): | |
if isinstance(dct, list): | |
prev, dct = dct, dct[int(x)] | |
else: | |
prev, dct = dct, dct[x] | |
else: | |
prev, dct = dct, dct[x] | |
return prev[x] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment