根据多个键或多个键合并或合并字典 [英] Combine or merge dictionaries based on more than one key or multi keys

查看:234
本文介绍了根据多个键或多个键合并或合并字典的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我整个上午都在搜索,但是大多数合并示例仅基于一个键,而在多个键上却找不到任何内容.

I've been searching all morning but most examples of merging was based on only one key, I couldn't find anything on multiple keys.

x = [
    {'pid':111, 'sid':6, 'eid':123, 'x_qty':30},
    {'pid':222, 'sid':56, 'eid':6212, 'x_qty':2}
    ]

y = [
    {'pid':111, 'sid':6, 'eid':123, 'y_qty':123},
    {'pid':333, 'sid':56, 'eid':6212, 'y_qty':112}
    ]

pid = 111,sid = 6,eid = 123的值在x和y中都匹配,然后合并为一条记录.如果它们不匹配,则按原样将其带来.

Values of pid=111, sid=6, eid=123 match in both x and y, then combine as one record. If they don't match, just bring it over as is.

我想要的最终结果:

z = [
    {'pid': 111, 'sid': 6, 'eid': 123, 'x_qty': 30, 'y_qty': 123},
    {'pid': 222, 'sid': 56, 'eid': 6212, 'x_qty': 2},
    {'pid': 333, 'sid': 56, 'eid': 6212, 'y_qty': 112}
    ]

推荐答案

这是重新锁定元组的方法:

This is re-keying off a tuple:

>>> from operator import itemgetter
>>> from collections import defaultdict
>>> data = defaultdict(dict)
>>> f = itemgetter('pid', 'sid', 'eid')
>>> for d in [*x, *y]:
...     data[f(d)].update(d)
...     
>>> list(data.values())
[{'eid': 123, 'pid': 111, 'sid': 6, 'x_qty': 30, 'y_qty': 123},
 {'eid': 6212, 'pid': 222, 'sid': 56, 'x_qty': 2},
 {'eid': 6212, 'pid': 333, 'sid': 56, 'y_qty': 112}]

这篇关于根据多个键或多个键合并或合并字典的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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