Skip to content

Instantly share code, notes, and snippets.

@manasmbellani
Created August 21, 2022 04:48
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 manasmbellani/279d2d64f494d9f03ea03efee105c9f0 to your computer and use it in GitHub Desktop.
Save manasmbellani/279d2d64f494d9f03ea03efee105c9f0 to your computer and use it in GitHub Desktop.
flatten_dict_to_csv.py - Flattens a Dictionary into a single dictionary that can be written to a CSV file
#!/usr/bin/env python3
import json
dictionary = {
'duration': 720,
'language': 'sv',
'link': 'https://vimeo.com/neweuropefilmsale/incidentbyabank',
'name': 'INCIDENT BY A BANK',
'test': {
'test2': {
'test2': [1,2,3],
}
},
'user': {
'link': 'https://vimeo.com/neweuropefilmsales',
'location': 'Warsaw, Poland',
'name': 'New Europe Film Sales'
}
}
def flatten(current: dict, path: str=".", result: dict={}):
if isinstance(current, dict):
for key in current:
if path == ".":
new_path = path + key
else:
new_path = path + "." + key
flatten(current[key], new_path, result)
else:
result[path] = str(current)
return result
result = flatten(dictionary)
print(json.dumps(result, indent=4))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment