Created
April 30, 2019 09:31
-
-
Save valericus/933729dc9815c1b584e0bade425cf2e4 to your computer and use it in GitHub Desktop.
Flatten nested dictionary
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
def flatten(dictionary, prefix = list(), sep='.'): | |
""" | |
Trivial function designed to make nested JSON suitable for | |
writing as CSV file. | |
>>> flatten( | |
{ | |
'foo': 'bar', | |
'buz': { | |
'foo1': 1, | |
'foo2: { | |
'a': True, | |
'b': False | |
} | |
} | |
} | |
) | |
{ | |
'foo': 'bar', | |
'buz.foo1': 1, | |
'buz.foo2.a': True, | |
'buz.foo2.b': False | |
} | |
:param dictionary: incoming dictionary | |
:param prefix: prefix of key in flattened dictionary, used for recursive calls | |
:param sep: used to separate keys of different levels | |
:return: dictionary with flat structure | |
""" | |
result = dict() | |
for key, value in dictionary.items(): | |
if isinstance(value, dict): | |
result.update(flatten(value, prefix + [key])) | |
else: | |
result[sep.join(prefix + [key])] = value | |
return result |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment