【问题标题】:How to join 2 lists of dicts in python?如何在 python 中加入 2 个字典列表?
【发布时间】:2015-08-25 03:06:26
【问题描述】:

我有 2 个这样的列表:

l1 = [{'a': 1, 'b': 2, 'c': 3, 'd': 4}, {'a': 5, 'b': 6, 'c': 7, 'd': 8}]

l2 = [{'a': 5, 'b': 6, 'e': 100}, {'a': 1, 'b': 2, 'e': 101}]

我想获得一个列表l3,它是l1l2 的连接,其中'a''b' 的值在l1l2 中相等 即

l3 = [{'a': 1, 'b: 2, 'c': 3, 'd': 4, 'e': 101}, {'a': 5, 'b: 6, 'c': 7, 'd': 8, 'e': 100}]

我该怎么做?

【问题讨论】:

    标签: python list python-2.7


    【解决方案1】:

    您应该将结果累积到字典中。你应该使用 'a' 和 'b' 的值来形成这个字典的键

    在这里,我使用了defaultdict 来累积条目

    l1 = [{'a': 1, 'b': 2, 'c': 3, 'd': 4}, {'a': 5, 'b': 6, 'c': 7, 'd': 8}]
    l2 = [{'a': 5, 'b': 6, 'e': 100}, {'a': 1, 'b': 2, 'e': 101}]
    
    from collections import defaultdict
    D = defaultdict(dict)
    for lst in l1, l2:
        for item in lst:
            key = item['a'], item['b']
            D[key].update(item)
    
    l3 = D.values()
    print l3
    

    输出:

    [{'a': 1, 'c': 3, 'b': 2, 'e': 101, 'd': 4}, {'a': 5, 'c': 7, 'b': 6, 'e': 100, 'd': 8}]
    

    【讨论】:

      【解决方案2】:

      简单的列表操作也能帮到你:

      l1 = [{'a': 1, 'b': 2, 'c': 3, 'd': 4}, {'a': 5, 'b': 6, 'c': 7, 'd': 8}]
      l2 = [{'a': 5, 'b': 6, 'e': 100}, {'a': 1, 'b': 2, 'e': 101}]
      l3 = []
      
      for i in range(len(l1)):
          for j in range(len(l2)):
              if l1[i]['a'] == l2[j]['a'] and l1[i]['b'] == l2[j]['b']:
                  l3.append(dict(l1[i]))
                  l3[i].update(l2[j])
      

      【讨论】:

      • 您应该使用== 而不是is 来比较值
      • @JohnLaRooy,但我记得有一次我读到 'is' 比 '==' 快...nop?
      • 可能,因为is 只比较身份。您在这里只能侥幸逃脱,因为您正在使用非常小的 int 值进行测试,这些值是被实习的。 == 是正确比较值的唯一方法
      • @JohnLaRooy...好的,感谢您的提醒.. :)
      【解决方案3】:

      我的方法是通过 key 对组合列表进行排序,即键 a + b。之后,对每组key相似的字典进行组合:

      from itertools import groupby
      
      def ab_key(dic):
          return dic['a'], dic['b']
      
      def combine_lists_of_dicts(list_of_dic1, list_of_dic2, keyfunc):
          for key, dic_of_same_key in groupby(sorted(list_of_dic1 + list_of_dic2, key=keyfunc), keyfunc):
              combined_dic = {}
              for dic in dic_of_same_key:
                  combined_dic.update(dic)
              yield combined_dic
      
      l1 = [{'a': 1, 'b': 2, 'c': 3, 'd': 4}, {'a': 5, 'b': 6, 'c': 7, 'd': 8}]
      l2 = [{'a': 5, 'b': 6, 'e': 100}, {'a': 1, 'b': 2, 'e': 101}]
      
      for dic in combine_lists_of_dicts(l1, l2, ab_key):
          print dic
      

      讨论

      • 函数ab_key返回一个值的元组,键为ab,用于对分组进行排序
      • groupby 函数将所有具有相似键的字典组合在一起
      • 此解决方案的效率低于 John La Rooy,但应该适用于小型列表

      【讨论】:

        【解决方案4】:

        使用 pandas 可以实现一个不错且快速的解决方案。

        l1 = [{'a': 1, 'b': 2, 'c': 3, 'd': 4}, {'a': 5, 'b': 6, 'c': 7, 'd': 8}]
        l2 = [{'a': 5, 'b': 6, 'e': 100}, {'a': 1, 'b': 2, 'e': 101}]
        
        import pandas as pd
        pd.DataFrame(l1).merge(pd.DataFrame(l2), on=['a','b']).to_dict('records')
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2017-05-04
          • 1970-01-01
          • 1970-01-01
          • 2020-12-06
          • 2022-11-09
          • 1970-01-01
          • 2020-03-15
          • 2020-09-18
          相关资源
          最近更新 更多