【问题标题】:How to merge list of dict with same keys?如何将dict列表与相同的键合并?
【发布时间】:2019-11-16 02:47:16
【问题描述】:

我有一个清单:

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

我想关注 o/p:

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

【问题讨论】:

    标签: list dictionary merge key


    【解决方案1】:

    试试这个代码:

    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']}
    

    【讨论】:

      猜你喜欢
      • 2021-07-11
      • 1970-01-01
      • 2021-06-22
      • 1970-01-01
      • 1970-01-01
      • 2020-02-25
      • 2021-07-03
      • 1970-01-01
      • 2017-11-01
      相关资源
      最近更新 更多