Created
November 19, 2019 14:59
-
-
Save classmember/c3fbfc37bdc79ae602f5321118f98a2a to your computer and use it in GitHub Desktop.
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 DictQuery(dict): | |
''' | |
source: | |
https://www.haykranen.nl/2016/02/13/handling-complex-nested-dicts-in-python/?fbclid=IwAR1QG8j1zzjTraJKQsFqf6wrvW1hV622GtWSsEOlfWCwzEZI_NBmyp9IOmk | |
Usage: | |
>>> # Complex Dictionary | |
>>> animals = [ | |
{ | |
"animal" : { | |
"type" : "bunny" | |
} | |
}, | |
{ | |
"animal" : {} | |
}, | |
{} | |
] | |
>>> # Getting nested "type" safely from "animal" | |
>>> for item in animals: | |
print DictQuery(item).get("animal/type") | |
bunny | |
{} | |
None | |
''' | |
def get(self, path, default = None): | |
keys = path.split("/") | |
val = None | |
for key in keys: | |
if val: | |
if isinstance(val, list): | |
val = [ v.get(key, default) if v else None for v in val] | |
else: | |
val = val.get(key, default) | |
else: | |
val = dict.get(self, key, default) | |
if not val: | |
break; | |
return val |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment