Skip to content

Instantly share code, notes, and snippets.

@valericus
Created April 30, 2019 09:31
Show Gist options
  • Save valericus/933729dc9815c1b584e0bade425cf2e4 to your computer and use it in GitHub Desktop.
Save valericus/933729dc9815c1b584e0bade425cf2e4 to your computer and use it in GitHub Desktop.
Flatten nested dictionary
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