Skip to content

Instantly share code, notes, and snippets.

@kleontev
Created February 23, 2022 04:50
Show Gist options
  • Save kleontev/a5f5fa924399646bede159d742bae3c9 to your computer and use it in GitHub Desktop.
Save kleontev/a5f5fa924399646bede159d742bae3c9 to your computer and use it in GitHub Desktop.
helper methods to access/modify nested dictionary structure in python
from typing import (
Any,
Dict,
Optional,
Union,
Tuple,
Hashable,
List
)
RAISE_IF_MISSING = object()
DictKeys = Union[List[Hashable], Tuple[Hashable, ...]]
def get_value_at(
d: Dict,
path: DictKeys,
default: Optional[Any] = None
) -> Any:
value = d
for p in path:
try:
value = value[p]
except KeyError:
if default is RAISE_IF_MISSING:
raise
return default
return value
def set_value_at(
d: Dict,
path: DictKeys,
value: Any
) -> Dict:
# does NOT copy the dict
# modifies it and returns it
if not path:
raise ValueError('path must not be empty')
subdict = d
for p in path[:-1]:
assert isinstance(subdict, dict)
if p not in subdict:
subdict[p] = {}
subdict = subdict[p]
subdict[path[-1]] = value
return d
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment