简体   繁体   English

在相同的键和值上合并两个 python 字典

[英]Merge two python dictionaries on the same key and value

For example I have two dictionaries d1 and d2例如我有两个字典 d1 和 d2

d1 = {'a': ['b','c'], 'd': ['e', 'f']}
d2 = {'b':[1, 2], 'c': [3, 4], 'd': [5, 6], 'e': [7, 8], 'f': [9, 10]}

I expect a new dictionary d3 that looks like我期待一个看起来像的新字典 d3

d3 = {'a':{'b':[1, 2], 'c': [3, 4]}, 'd': {'e': [7, 8], 'f': [9, 10]}}

I have tried all kinds of looping but it does not work.我尝试了各种循环,但它不起作用。

You can use dict comprehension -您可以使用听写理解-

d1 = {'a': ['b','c'], 'd': ['e', 'f']}
d2 = {'b':[1, 2], 'c': [3, 4], 'd': [5, 6], 'e': [7, 8], 'f': [9, 10]}
d3 = {k1:{v:d2[v] for v in v1} for k1, v1 in d1.items()}
print(d3)

Output: Output:

{'a': {'b': [1, 2], 'c': [3, 4]}, 'd': {'e': [7, 8], 'f': [9, 10]}}

Here, for every key( k1 ) in d1 , we are creating an entry in d3 and the corresponding value is another dict, where key is values from first dict and corresponding value in d2 for the key.在这里,对于d1中的每个键( k1 ),我们在d3中创建一个条目,对应的值是另一个字典,其中键是来自第一个字典的值和d2中键的对应值。

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

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