python的字典合并有相同的,Python 3.x:合并两个具有相同键和值的字典

Python version: 3.x

I have two dictionaries with same keys and the values are arrays. Most of the questions I saw here, for the required purpose, have only one value for each key. What I want is to merge those two dictionaries with values as joined array. Maybe below would clear:

What I've:

d1 = {(1, "Autumn"): np.array([2.5, 4.5, 7.5, 9.5]), (1, "Spring"): np.array([10.5, 11.7, 12.3, 15.0])}

d2 = {(1, "Autumn"): np.array([10.2, 13.3, 15.7, 18.8]), (1, "Spring"): np.array([15.6, 20, 23, 27])}

I've tried:

d3 = {**d1, **d2}

What I want:

d3 = {(1, "Autumn"): np.array([2.5, 4.5, 7.5, 9.5, 10.2, 13.3, 15.7, 18.8]), (1, "Spring"): np.array([10.5, 11.7, 12.3, 15.0, 15.6, 20, 23, 27])}

Am I missing something here? Please help!

解决方案

Try this:

>>> import numpy as np

>>> d1 = {(1, "Autumn"): np.array([2.5, 4.5, 7.5, 9.5]), (1, "Spring"): np.array([10.5, 11.7, 12.3, 15.0])}

>>> d2 = {(1, "Autumn"): np.array([10.2, 13.3, 15.7, 18.8]), (1, "Spring"): np.array([15.6, 20, 23, 27])}

>>> d3 = {k: np.concatenate((d1.get(k, np.array([])), d2.get(k, np.array([])))) for k in set(d1.keys()).union(set(d2.keys()))}

>>> d3

{(1, 'Spring'): array([10.5, 11.7, 12.3, 15. , 15.6, 20. , 23. , 27. ]), (1, 'Autumn'): array([ 2.5, 4.5, 7.5, 9.5, 10.2, 13.3, 15.7, 18.8])}

Notes:

It's a dict comprehension

First, a union of the keys in the 2 dicts is computed, to make sure that no key is left aside (for that, the keys in each dict are converted into a set)

For each element in the above set, get the corresponding array (empty one if the key is not present) from each dict, and concatenate them

This is the Pythonic (and also general) approach, my numpy knowledge is somewhere close to 0 (I'm sure that it's pretty obvious from the code snippet - it looks awfully complex with all those parentheses), it's extremely likely that numpy has something to make things in a much more elegant manner

[SO]: How to merge two dictionaries in a single expression? desired output and the current one (considering that the dict values are simply iterables (whether they are Python or numpy or any other kind is irrelevant)) are 2 different (and equally correct) approaches of the merge concept regarding dicts, in case of common keys:

One only keeps the value from the last dict

The other sums (whatever sum would mean for the operands) all of them

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值