Skip to content

Instantly share code, notes, and snippets.

@AlmightyOatmeal
Last active May 8, 2018 22:41
Show Gist options
  • Save AlmightyOatmeal/ac0489cb722f03230345fdef205ec88e to your computer and use it in GitHub Desktop.
Save AlmightyOatmeal/ac0489cb722f03230345fdef205ec88e to your computer and use it in GitHub Desktop.
Fun with Python dictionaries! Works on Python 2.7.x.
def flatten(obj, parent_key=None, sep='.'):
"""Flattens multi-level dictionary to a single-level dictionary.
:param obj: Dictionary object to flatten.
:type obj: dict
:param parent_key: (optional) Prefix for the flattened key. (default: None)
:type parent_key: basestring, str, or unicode
:param sep: (optional) Separator for the nested key names. (default: '.')
:type sep: basestring, str, or unicode
:return: Sexy flattened dictionary.
:rtype: dict
"""
items = []
for obj_key, obj_val in obj.items():
obj_key = obj_key.replace(' ', '_')
# obj_key = regex_non_alphanumeric_chars.sub('', obj_key)
new_key = '{}{}{}'.format(parent_key, sep, obj_key) if parent_key else obj_key
if isinstance(obj_val, dict):
items.extend(flatten(obj_val, new_key, sep=sep).items())
else:
items.append([new_key, obj_val])
return dict(items)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment