简体   繁体   English

将一个嵌套字典的值更新为另一个具有字典列表的字典

[英]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我可以根据值为 dict2 的键替换 dict1 中的值

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 中找到 C 和 D 并用 dict2 中的 C 和 D 列表替换输出应该是这样的:

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在不影响 dict 1 中的原始键 A 和 B 的情况下,我们还可以创建一个新的字典复制 dict1 并进行修改..但 dict1 的结构应保持不变

Possibly, you haven't written dict2 properly, it neither a dictionary nor a set.可能是您没有正确编写dict2 ,它既不是字典也不是集合。 Maybe this ( dict2={'s1':[{'C':'3a','D':'4a'},{'C':'3b','D':'4b'}], 'B': {'E':'5a','F':'6a'}} ) is what you meant.也许这个( dict2={'s1':[{'C':'3a','D':'4a'},{'C':'3b','D':'4b'}], 'B': {'E':'5a','F':'6a'}} ) 就是你的意思。

If this assumption is correct, the you can change the value of key A in dict1 this way:如果这个假设是正确的,您可以通过这种方式更改 dict1 中键 A 的值:

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

Result结果

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM