【问题标题】:how can i create dictionary of list from to different lists我如何创建从不同列表到不同列表的列表字典
【发布时间】:2020-02-26 23:51:54
【问题描述】:

我有两个列表:

a = [{'id':1,'qty':2,'name':x},{'id':2,'qty':5,'name':b}]
b = [{'id':1,'name':x , 'barcode': 1578563445},{'id':2,'name':b , 'barcode': 9856754}]

我想制作如下列表或字典:

c= [
    {'id':1,'qty':2,'name':x,'barcode': 1578563445 },
    {'id':2,'qty':5,'name':b ,'barcode': 9856754 }
]

【问题讨论】:

标签: python arrays list


【解决方案1】:

你可以这样做:

a = [{'id':1,'qty':2,'name':'x'},
    {'id':2,'qty':5,'name':'b'}]
b= [{'id':1,'name':'x' , 'barcode': 1578563445},
    {'id':2,'name':'b' , 'barcode': 9856754}]


for elem_b in b:
    for elem_a in a:
        if elem_a['id'] == elem_b['id']:
            elem_a.update(elem_b)

输出:

[{'id': 1, 'qty': 2, 'name': 'x', 'barcode': 1578563445}, {'id': 2, 'qty': 5, 'name': 'b', 'barcode': 9856754}]

【讨论】:

    【解决方案2】:
    c = []
    for d in a:
        u = [x for x in b if x['id'] == d['id']]
        for i in u:
            d.update(i)
        c.append(d)
    

    【讨论】:

      【解决方案3】:
      a = [{'id':1,'qty':2,'name':x},{'id':2,'qty':5,'name':b}]
      b = [{'id':1,'name':x , 'barcode': 1578563445},{'id':2,'name':b , 'barcode': 9856754}]    
      
      for x in b:
          c = [z.update(x) for z in a if z['id'] == x['id']]  
      
      print(a)
      

      dict.update() 解释。

      【讨论】:

        【解决方案4】:

        这可能不是最有效的解决方案,但我认为这是一个相当简单和直观的实现。

        c = []
        for entry in a + b:
        
            # Loop through c to check if a matching id exists
            found = False
            for j in range(len(c)):
                if c[j]['id'] == entry['id']:
        
                    # update all fields if id matches
                    for k in entry.keys():
                        c[j][k] = entry[k]
                        found = True  # Set flag to not add new entry
                    break
            if not found:  # Only append if we did not find an existing match
                c.append(entry)
        
        return c
        

        我不确定您想如何处理相互冲突的信息,例如同一个 ID 有两个不同的条形码。如果这可能是一个问题,这将需要一些额外的条款来处理这种情况。

        【讨论】:

          【解决方案5】:

          您可以使用zip 将两个字典组合到一个列表理解中。此外,您的示例数据在名称周围缺少引号。

          a = [{'id':1,'qty':2,'name':'x'},{'id':2,'qty':5,'name':'b'}]
          b = [{'id':1,'name':'x' , 'barcode': 1578563445},{'id':2,'name':'b' , 'barcode': 9856754}]
          
          c = [dict({*a1.items(), *b1.items()}) for a1, b1 in zip(a,b)]
          

          c 的值是:

          [{'name': 'x', 'id': 1, 'barcode': 1578563445, 'qty': 2}, {'qty': 5, 'id': 2, 'barcode': 9856754, 'name': 'b'}]
          

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 2020-01-11
            • 1970-01-01
            • 1970-01-01
            • 2018-09-15
            • 2021-07-03
            • 2018-12-17
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多