具有相同键值对的字典列表的并集

时间:2017-09-26 06:04:33

标签: python list dictionary

我有一个如下所示的列表,其中包含一些词典。

dlist=[
{
    "a":1,
    "b":[1,2]
},
{
    "a":3,
    "b":[4,5]
},
{
    "a":1,
    "b":[1,2,3]
}
]

我希望结果如下所示

dlist=[
{
    "a":1,
    "b":[1,2,3]
},
{
    "a":3,
    "b":[4,5]
}
]

我可以使用循环和比较的多次迭代来解决这个问题,但是有一种pythonic方法吗?

2 个答案:

答案 0 :(得分:1)

这是一个使用临时defaultdict的解决方案:

from collections import defaultdict
dd = defaultdict(set)                              # create temporary defaultdict
for d in dlist: dd[d["a"]] |= set(d["b"])          # union set(b) for each a
l = [{"a":k, "b":list(v)} for k,v in dd.items()]   # generate result list

Try it online!

答案 1 :(得分:0)

如果我的理解是正确的

uniques, theNewList = set(), []
for d in dlist:
    cur = d["a"] # Avoid multiple lookups of the same thing
    if cur not in uniques:
        theNewList.append(d)
    uniques.add(cur)
print(theNewList)
相关问题