[英]union of list of dictionaries having same key value pair
我有一個如下所示的列表,其中包含一些字典。
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的方法嗎?
這是使用臨時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
如果我的理解是正確的
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)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.