How would I flatten a nested dictionary in Python 3? -
this question has answer here:
is there native function flatten nested dictionary output dictionary keys , values in format:
_dict2 = { 'this.is.an.example': 2, 'this.is.another.value': 4, 'this.example.too': 3, 'example': 'fish' }
assuming dictionary have several different value types, how should go iterating dictionary?
you want traverse dictionary, building current key , accumulating flat dictionary. example:
def flatten(current, key, result): if isinstance(current, dict): k in current: new_key = "{0}.{1}".format(key, k) if len(key) > 0 else k flatten(current[k], new_key, result) else: result[key] = current return result result = flatten(my_dict, '', {})
using it:
print(flatten(_dict1, '', {})) {'this.example.too': 3, 'example': 'fish', 'this.is.another.value': 4, 'this.is.an.example': 2}
Comments
Post a Comment