Created
July 20, 2017 00:46
-
-
Save marksweissma/331d9521be7ea58f542fc3dbf2b3fe91 to your computer and use it in GitHub Desktop.
unpack nested dicts by concatenating keys
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
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