Search code examples
pythondictionarynestedpandas-groupbydictionary-comprehension

Updating values of one nested dictionary to another having list of dictionaries


say we have two nested dictionaries:

dict1={'s1':{'A':{'C':'3','D':'4'},'B':{'E':'5','F':'6'}}}

dict2 = {'s1':[{'C':'3a','D':'4a'},{'C':'3b','D':'4b'}], 'B': {'E':'5a','F':'6a'}}

I can replace the value in dict1 based on a key with value dict2

dict1['E']=dict2['E']

which will result in ..

dict1={'s1':{'A':{'C':'3','D':'4'},'B':{'E':'5a','F':'6'}}}

Now I want to find, C and D in dict1 and replace with list of C and D from dict2 Output should be like:

dict1={'s1':{'A':[{'C':'3a','D':'4a'},{'C':'3b','D':'4b'}],'B':{'E':'5a','F':'6'}}}

without affecting original keys A and B in dict 1 we can also create a new dictionary copying dict1 and make modifications.. but the structure of dict1 should remain intact


Solution

  • Possibly, you haven't written dict2 properly, it neither a dictionary nor a set. Maybe this (dict2={'s1':[{'C':'3a','D':'4a'},{'C':'3b','D':'4b'}], 'B': {'E':'5a','F':'6a'}}) is what you meant.

    If this assumption is correct, the you can change the value of key A in dict1 this way:

    dict1['s1']['A'] = dict2['s1']
    print(dict1)
    

    Result

    {'s1': {'A': [{'C': '3a', 'D': '4a'}, {'C': '3b', 'D': '4b'}], 'B': {'E': '5', 'F': '6'}}}