Skip to content

Instantly share code, notes, and snippets.

@marksweissma
Created July 20, 2017 00:46
Show Gist options
  • Save marksweissma/331d9521be7ea58f542fc3dbf2b3fe91 to your computer and use it in GitHub Desktop.
Save marksweissma/331d9521be7ea58f542fc3dbf2b3fe91 to your computer and use it in GitHub Desktop.
unpack nested dicts by concatenating keys
def unpack_dict(d, keys=None, passed=None, filterNone=True):
"""
Unpack nested dictionary with _ separted keys
:param dict d: nested dictionary to unpack
:param list keys: sequence of access keys
:param dict passed: dict to update with flattened keys
:param bool filterNone: filter out keys where value is None
:return: flattened dict
:rtype: dict
"""
if passed is None:
passed = {}
if keys is None:
keys = []
for key, value in d.iteritems():
if isinstance(value, dict):
passed = unpack_dict(value, keys + [key], passed, filterNone)
elif not filterNone or value is not None:
passed["_".join(keys + [key])] = value
return passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment