Created
March 21, 2024 15:41
-
-
Save gyli/ee070dbb9e0a4f4b85512de00326d702 to your computer and use it in GitHub Desktop.
Accessing dict value with all keys in one string
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
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