Skip to content

Instantly share code, notes, and snippets.

@gyli
Created March 21, 2024 15:41
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 gyli/ee070dbb9e0a4f4b85512de00326d702 to your computer and use it in GitHub Desktop.
Save gyli/ee070dbb9e0a4f4b85512de00326d702 to your computer and use it in GitHub Desktop.
Accessing dict value with all keys in one string
class DynamicAccessDict(dict):
"""
A dict-like class that allows accessing LineCol object with multi-level keys in a list
Example:
config == {
'a': {
'b': 0, # int value
'c': [{'d': 3}] # list value
}
}
d = DynamicAccessLineColDict(config)
# Get a config value with a list of parameters
d.get_by_keys(['a', 'b']) # 0
# Get a list value with a list of parameters and indexes
d.get_by_keys(['a', 'c', 0, 'd']) # 3
# Check if a key-value pair exists with given list of keys
d.key_exists(['a', 'a']) # False
"""
def get_by_keys(self, keys: Sequence):
return reduce(operator.getitem, keys, self)
def set_by_keys(self, keys: Sequence, val) -> None:
reduce(lambda d, k: d.setdefault(k, {}), keys[:-1], self)[keys[-1]] = val
def has_keys(self, keys: Sequence) -> bool:
try:
reduce(operator.getitem, keys, self)
return True
except (KeyError, TypeError):
return False
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment