在一个键上连接两个字典列表 [英] join two lists of dictionaries on a single key
问题描述
给定以 m
字典作为元素的 n
列表,我想生成一个新列表,其中包含一组连接的字典.每个字典都保证有一个称为索引"的键,但可以有一组任意的键.非索引键永远不会跨列表重叠.例如,想象以下两个列表:
Given n
lists with m
dictionaries as their elements, I would like to produce a new list, with a joined set of dictionaries. Each dictionary is guaranteed to have a key called "index", but could have an arbitrary set of keys beyond that. The non-index keys will never overlap across lists. For example, imagine the following two lists:
l1 = [{"index":1, "b":2}, {"index":2, "b":3}, {"index":3, "green":"eggs"}]
l2 = [{"index":1, "c":4}, {"index":2, "c":5}]
("b"
永远不会出现在 l2
中,因为它出现在 l1
中,类似地,"c"
永远不会出现在 l1
中,因为它出现在 l2
)
("b"
would never appear in l2
, since it appeared in l1
, and similarly, "c"
would never appear in l1
, since it appeared in l2
)
我想生成一个连接列表:
I would like to produce a joined list:
l3 = [{"index":1, "b":2, "c":4},
{"index":2, "b":3, "c":5},
{"index":3, "green":"eggs"}]
在 Python 中执行此操作的最有效方法是什么?
What is the most efficient way to do this in Python?
推荐答案
from collections import defaultdict
l1 = [{"index":1, "b":2}, {"index":2, "b":3}, {"index":3, "green":"eggs"}]
l2 = [{"index":1, "c":4}, {"index":2, "c":5}]
d = defaultdict(dict)
for l in (l1, l2):
for elem in l:
d[elem['index']].update(elem)
l3 = d.values()
# l3 is now:
[{'b': 2, 'c': 4, 'index': 1},
{'b': 3, 'c': 5, 'index': 2},
{'green': 'eggs', 'index': 3}]
EDIT:由于 l3
不能保证被排序(.values()
返回没有特定顺序的项目),你可以这样做正如@user560833 建议的那样:
EDIT: Since l3
is not guaranteed to be sorted (.values()
returns items in no specific order), you can do as @user560833 suggests:
from operator import itemgetter
...
l3 = sorted(d.values(), key=itemgetter("index"))
这篇关于在一个键上连接两个字典列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!