Skip to content

Instantly share code, notes, and snippets.

@classmember
Created November 19, 2019 14:59
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 classmember/c3fbfc37bdc79ae602f5321118f98a2a to your computer and use it in GitHub Desktop.
Save classmember/c3fbfc37bdc79ae602f5321118f98a2a to your computer and use it in GitHub Desktop.
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