Skip to content

Instantly share code, notes, and snippets.

@lucidyan
Created July 3, 2018 14:14
Show Gist options
  • Save lucidyan/5202af2fb7a45795861c3fafb73aa7ff to your computer and use it in GitHub Desktop.
Save lucidyan/5202af2fb7a45795861c3fafb73aa7ff to your computer and use it in GitHub Desktop.
Non-recursive flatten nested dictionaries in Python3
# Non-recursive flatten nested dictionaries in Python3
# Source: https://codereview.stackexchange.com/a/173483/173155
from itertools import chain, starmap
def flatten_dict(dictionary):
"""Flatten a nested dictionary structure"""
def unpack(parent_key, parent_value):
"""Unpack one level of nesting in a dictionary"""
try:
items = parent_value.items()
except AttributeError:
# parent_value was not a dict, no need to flatten
yield (parent_key, parent_value)
else:
for key, value in items:
yield (parent_key + (key,), value)
# Put each key into a tuple to initiate building a tuple of subkeys
dictionary = {(key,): value for key, value in dictionary.items()}
while True:
# Keep unpacking the dictionary until all value's are not dictionary's
dictionary = dict(chain.from_iterable(starmap(unpack, dictionary.items())))
if not any(isinstance(value, dict) for value in dictionary.values()):
break
return dictionary
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment