Skip to content

Instantly share code, notes, and snippets.

@headsrooms
Created October 17, 2017 08:41
Show Gist options
  • Save headsrooms/750df7536a04be6e26222a3b922117a0 to your computer and use it in GitHub Desktop.
Save headsrooms/750df7536a04be6e26222a3b922117a0 to your computer and use it in GitHub Desktop.
Flatten nested dicts
def flatten_dict(d):
def expand(key, value):
if isinstance(value, dict):
return [(key + '.' + k, v) for k, v in flatten_dict(value).items()]
else:
return [(key, value)]
items = [item for k, v in d.items() for item in expand(k, v)]
return dict(items)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment