【问题标题】:merge two lists of dictionaries without ids in Python在 Python 中合并两个没有 id 的字典列表
【发布时间】:2018-07-09 13:55:12
【问题描述】:

我有两个这样的字典列表:

list1 =[{doc:1,pos_ini:5,pos_fin:10},{doc:1,pos_ini:7,pos_fin:12},{doc:2,pos_ini:5,pos_fin:10},**{doc:7,pos_ini:5,pos_fin:10}**]

list2 =
[{doc:1,pos_ini:5,pos_fin:10},**{doc:1,pos_ini:6,pos_fin:7}**,{doc:1,pos_ini:7,pos_fin:12},{doc:2,pos_ini:5,pos_fin:10},**{doc:2,pos_ini:25,pos_fin:30}**]

list2 有两个list1 没有的元素,list1 有一个list2 没有的元素。

我需要一个合并所有元素的list_result

list_result =[{doc:1,pos_ini:5,pos_fin:10},**{doc:1,pos_ini:6,pos_fin:7}**,{doc:1,pos_ini:7,pos_fin:12},{doc:2,pos_ini:5,pos_fin:10},
**{doc:2,pos_ini:25,pos_fin:30}**,**{doc:7,pos_ini:5,pos_fin:10}**]

在 Python 中最好的方法是什么?谢谢!

【问题讨论】:

    标签: python list dictionary merge


    【解决方案1】:

    在 Python 中,内置的 set 集合非常适合此操作。问题是集合需要 hashable 元素,因此您必须将 dict 转换为一组元组:

    [dict(items) for items in set(tuple(sorted(d.items())) for d in (list1 + list2))]
    

    【讨论】:

      【解决方案2】:

      您可以使用 frozenset() 将每个字典 items() 散列到字典中,然后简单地获取分配的值:

      list({frozenset(x.items()): x for x in list1 + list2}.values())
      

      或者使用map() 应用于集合理解:

      list(map(dict, {frozenset(x.items()) for x in list1 + list2}))
      

      或者甚至只使用列表推导:

      [dict(d) for d in {frozenset(x.items()) for x in list1 + list2}]
      

      这将给出一个无序结果:

      [{'doc': 1, 'pos_fin': 10, 'pos_ini': 5},
       {'doc': 1, 'pos_fin': 12, 'pos_ini': 7},
       {'doc': 2, 'pos_fin': 10, 'pos_ini': 5},
       {'doc': 7, 'pos_fin': 10, 'pos_ini': 5},
       {'doc': 1, 'pos_fin': 7, 'pos_ini': 6},
       {'doc': 2, 'pos_fin': 30, 'pos_ini': 25}]
      

      注意:如果需要订单,您可以在此处使用collections.OrderedDict()

      from collections import OrderedDict
      
      list(OrderedDict((frozenset(x.items()), x) for x in list1 + list2).values())
      

      这给出了这个有序结果:

      [{'doc': 1, 'pos_fin': 10, 'pos_ini': 5},
       {'doc': 1, 'pos_fin': 12, 'pos_ini': 7},
       {'doc': 2, 'pos_fin': 10, 'pos_ini': 5},
       {'doc': 7, 'pos_fin': 10, 'pos_ini': 5},
       {'doc': 1, 'pos_fin': 7, 'pos_ini': 6},
       {'doc': 2, 'pos_fin': 30, 'pos_ini': 25}]
      

      【讨论】:

        【解决方案3】:

        你可以用这些值创建一个集合,而不是字典,它需要被转换成一个像元组这样的可散列对象:

        unique_list = set(tuple(dictionary.items())) for dictionary in list1 + list2)
        

        然后可以再次转换回字典和列表格式:

        l = []
        for item in unique_list:
            l.append(dict(item))
        

        上面的方法应该可以工作。

        【讨论】:

        • 在 3.6.1 中:TypeError: unhashable type: 'dict_items'
        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2013-11-02
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-09-25
        相关资源
        最近更新 更多