List 如何合并具有相同键的dict列表?

List 如何合并具有相同键的dict列表?,list,dictionary,merge,key,List,Dictionary,Merge,Key,我有一份清单: list=[{'Query':'documents'},{'entity':'a'},{'value':'b'},{'entity':'c'},{'value':'d'},{'records':21}] 我要下列订单: d={'Query':['documents'],'entity':['a','c'],'value':['b','d'],'records':[21]} 尝试以下代码: list=[{'Query': 'documents'}, {'entity': 'a'}

我有一份清单:

list=[{'Query':'documents'},{'entity':'a'},{'value':'b'},{'entity':'c'},{'value':'d'},{'records':21}]
我要下列订单:

d={'Query':['documents'],'entity':['a','c'],'value':['b','d'],'records':[21]}
尝试以下代码:

list=[{'Query': 'documents'}, {'entity': 'a'}, {'value': 'b'}, {'entity': 'c'}, {'value': 'd'}, {'records':21}]
d={}
for i in list :
    for j,k in i.items():
        l = []
        if j in d:
            l = d[j]
            l.append(k)
            d[j] = l
        else:
            l.append(str(k))
            d[j]=l
print(d)
输出:

{'records': ['21'], 'value': ['b', 'd'], 'entity': ['a', 'c'], 'Query': ['documents']}