Skip to content Skip to sidebar Skip to footer

How To Flatten A Nested Dictionary?

Is there a native function to flatten a nested dictionary to an output dictionary where keys and values are in this format: _dict2 = { 'this.is.an.example': 2, 'this.is.another

Solution 1:

You want to traverse the dictionary, building the current key and accumulating the flat dictionary. For example:

defflatten(current, key, result):
    ifisinstance(current, dict):
        for k in current:
            new_key = "{0}.{1}".format(key, k) iflen(key) > 0else 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}

Post a Comment for "How To Flatten A Nested Dictionary?"