Last active
June 10, 2020 19:18
-
-
Save rgegriff/74050ef58dd7949d65498918fedb1f1b to your computer and use it in GitHub Desktop.
Code for walking a nested dictionary in python and turning it into a flat dictionary with dotted key names
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def linearize_dict(dct, prefix=None, part_sep="."): | |
"""Walk a nested dict, and flatten it""" | |
linearized = {} | |
for key, value in dct.items(): | |
# Ensure key doesn't already contain part_sep | |
if part_sep in key: | |
raise Exception("Part sep '%s' exists in key. Use a different part sep") | |
# Create prefixed version of this key if needed | |
if prefix == None: | |
prefixed_key = key | |
else: | |
prefixed_key = "%s%s%s"%(prefix, part_sep, key) | |
# Decend into dict if needed | |
if type(value) == dict: | |
linearized.update(linearize_dict(value, prefixed_key, part_sep)) | |
else: | |
linearized[prefixed_key] = value | |
return linearized | |
""" | |
nested_dict = { | |
"fruits": {"apple": True, "pear": True, "tomato": False}, | |
"author_states": {"willing_to_die_on_this_hill": True} | |
} | |
linearize_dict(nested_dict) -> {"fruits.apple" : True, | |
"fruits.pear": True, | |
"fruits.tomato": False, | |
"author_states.willing_to_die_on_this_hill": True | |
} | |
""" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment