Skip to content

Instantly share code, notes, and snippets.

@pcn
Last active July 29, 2021 18:37
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save pcn/a3a2031a15c3243dedd4c5afda98cfd7 to your computer and use it in GitHub Desktop.
Save pcn/a3a2031a15c3243dedd4c5afda98cfd7 to your computer and use it in GitHub Desktop.
Assoc-in and get-in for python
# 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