【问题标题】:Join two lists of dictionaries around a single non-unique key围绕单个非唯一键加入两个字典列表
【发布时间】:2011-11-30 19:00:06
【问题描述】:

我有 2 个字典列表,比如说:

l1 = [{"customer":"amy", "order":2}, {"customer":"amy", "order":3}, {"customer":"basil", "order":4}]
l2 = [{"customer":"amy", "died":"who fell down the stairs"}, {"customer":'basil', "died":"assaulted by bears"}]

我正在寻找一种优雅的方式来从 l2 获取密钥并将它们放入 l1。这是为了加入使用不同值作为索引的字典列表

该函数应该类似于 join(l1,l2,'customer'),并生成

l3 = [{"customer":"amy", "order":2,"died":"who fell down the stairs"}, {"customer":"amy", "order":3,"died":"who fell down the stairs"}, {"customer":"basil", "order":4,"died":"assaulted by bears"}}]

l3 中的每个字典都应该有一个字典。

如果 l1 和 l2 具有相同的非连接键但值不同,则 l2 优先。

l2 将具有唯一的加入键值。

现在我已经尝试了这段丑陋的代码:

l3 = []
rdict = {}
for i in range(len(l2)):
    rdict[l2[i][field]]=i
for d in l1: 
    l3.append(dict(d.items()+l2[rdict[d[field]]].items()))
return l3

the solution from this SO question 一样,但假设所有列表中只有一个索引。

谢谢

【问题讨论】:

    标签: python


    【解决方案1】:

    简单:

    SELECT *
    FROM l1, l2
    WHERE l1.customer = l2.customer
    

    ...开玩笑的...

    def join(t1,t2,column):
        result = []
        for entry in t2:
            for match in [d for d in t1 if d[column] == entry[column]]:
                result.append(dict((k,v) for k,v in entry.items()+match.items()))
        return result
    

    【讨论】:

      【解决方案2】:

      另一种答案...

      def diff(d1, d2, key):
          if d1[key] != d2[key]:
              return d1
          new_keys = list(set(d2) - set(d1))
          for new_key in new_keys:
              d1[new_key] = d2[new_key]
          return d1
      
      def join(l1, l2, key):
          l3 = l1
          for d2 in l2:
              l3 = map(lambda d1: diff(d1, d2, key), l3)
          return l3
      

      【讨论】:

        猜你喜欢
        • 2011-07-26
        • 1970-01-01
        • 1970-01-01
        • 2022-06-23
        • 2023-02-05
        • 1970-01-01
        • 1970-01-01
        • 2018-08-26
        • 1970-01-01
        相关资源
        最近更新 更多