Quantcast
Channel: Active questions tagged python - Stack Overflow
Viewing all articles
Browse latest Browse all 17071

Replace duplicate keys in a nested dictionary [closed]

$
0
0

I have a nested dictionary. My goal is to replace duplicate keys. If a key is matched with earlier level key, the key will be replaced in tha latter version with everything in the earlier version. For example, lets say I have an input like below:

data = {'key1': {'key1_1': "v1_1",'key1_2': "v1_2",     },'key2': 'v2','key3': {'key3_1': "v3_1",'key1': "v3_2",    }}

If the key1 is duplicate then key_1 under key3 will be replaced using the values of the first found key1 and key_1 will be deleted. For example, a dummy output will be like below:

data = {'key2': 'v2','key3': {'key3_1': "v3_1",'key1': {'key1_1': "v1_1",'key1_2': "v1_2",     },    }}

Can anyone suggest me any simple way to do this?

I have tried iterating over the nested dictionary for each elements. This way did not resulted any viable solution.

Later addition 1:The problem can be extended to deeper nested dictionary to ranging 5-6 level nest also. Used data is a simpler version of it.


Viewing all articles
Browse latest Browse all 17071

Latest Images

Trending Articles



Latest Images

<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>