如何使用相同的密钥合并多个数字? [英] How to merge multiple dicts with same key?

查看:117
本文介绍了如何使用相同的密钥合并多个数字?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这样的多个dicts /键值对:

I have multiple dicts/key-value pairs like this:

d1 = {key1: x1, key2: y1)  
d2 = {key1: x2, key2: y2)  

我希望结果为一个新的dict(以最有效的方式,如果可能的话):

I want the result to be a new dict (in most efficient way, if possible):

d = {key1: (x1, x2), key2: (y1, y2)}  

其实我想要结果d是:

d = {key1: (x1.x1attrib, x2.x2attrib), key2: (y1.y1attrib, y2.y2attrib)}  

但是,我猜,如果有人向我展示如何获得第一个结果,我可以弄清楚其余的。假设所有密钥总是存在于所有的数据中:

But, I am guessing if somebody shows me how to get the first result, I can figure out the rest.

推荐答案

ds = [d1, d2]
d = {}
for k in d1.iterkeys():
    d[k] = tuple(d[k] for d in ds)

这篇关于如何使用相同的密钥合并多个数字?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆