Created
August 11, 2018 11:09
-
-
Save jamesridgway/326e0a146ae976af0c7b797e19a5985d to your computer and use it in GitHub Desktop.
Use dot notation to recursively lookup data attributes in a dict
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
""" | |
NestedDict wrapper | |
""" | |
class NestedDict(dict): | |
def __getitem__(self, key_namespace): | |
if "." not in key_namespace: | |
return super(NestedDict, self).__getitem__(key_namespace) | |
keys = key_namespace.split('.') | |
val = self | |
for key in keys: | |
if isinstance(val, list): | |
val = val[int(key)] | |
else: | |
val = val[key] | |
return val | |
""" | |
Example below | |
""" | |
data = NestedDict({ | |
'name': { | |
'first': 'John', | |
'last': 'Smith' | |
}, | |
'age': 26, | |
'favourite_numbers': [3, 7, 11], | |
}) | |
print(data['name']) | |
print(data['name.first']) | |
print(data['name.last']) | |
print(data['age']) | |
print(data['favourite_numbers']) | |
print(data['favourite_numbers.2']) | |
print(data['favourite_numbers.0']) | |
print(data['favourite_numbers.1']) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment