[英]How to multiple key list values in two dictionaries
Eg I have the following例如我有以下内容
d1 = {'a': [100,300,34], 'b': [200,98,45], 'c':[450,567,300]}
d2 = {'d': [300,500,234], 'e': [300,500,234], 'f':[300,500,234]}
Want to get想要得到
d3 = {'ad': [400,800,268], 'be': [500,598,279], 'cf':[750,1067,534]}
I have the following in mind to start: for i, j in d1.items():
我有以下想法开始:
for i, j in d1.items():
for x, y in d2.items():
Here, I use a nested comprehension to achieve what you want.在这里,我使用嵌套理解来实现你想要的。 First, I take corresponding items in
d1
and d2
using zip()
.首先,我使用
zip()
在d1
和d2
中获取相应的项目。 Then, I concatenate their keys, making that the key of the new dict, and use a list comprehension to sum the elements of their respective lists, which gets set as the value in the new dict.然后,我连接它们的键,使其成为新字典的键,并使用列表推导式对各自列表的元素求和,并将其设置为新字典中的值。
d3 = {
i1[0] + i2[0]: [v1 + v2 for v1,v2 in zip(i1[1], i2[1])]
for i1,i2 in zip(d1.items(), d2.items())
}
# {'ad': [400, 800, 268], 'be': [500, 598, 279], 'cf': [750, 1067, 534]}
Note that, before Python 3.7, the 'order' of a dict was arbitrary.请注意,在 Python 3.7 之前,字典的“顺序”是任意的。 Now, when you call
.items()
, you'll get keys in the order they were most recently added or defined, but before that you could get them in any order, and so the above would not work.现在,当您调用
.items()
时,您将按照最近添加或定义的顺序获得键,但在此之前您可以按任何顺序获得它们,因此上述方法不起作用。
You can do something like this:你可以这样做:
d3 = {k1 + k2: [p + q for p, q in zip(d1[k1], d2[k2])] for k1, k2 in zip(d1.keys(), d2.keys())}
or要么
Without using dictionary comprehension:不使用字典理解:
d3 = {}
for k1, k2 in zip(d1.keys(), d2.keys()):
d3[k1 + k2] = [p + q for p, q in zip(d1[k1], d2[k2])]
Output: Output:
{'ad': [400, 800, 268], 'be': [500, 598, 279], 'cf': [750, 1067, 534]}
Make sure to use an OrderedDict if you want to maintain the order of the keys.如果要维护键的顺序,请确保使用OrderedDict 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.