首页 > 解决方案 > Python:字典列表 - 复制字典

问题描述

我有 2 个字典列表:

我想遍历每个需求和每个供应,如果值 ('val') 匹配,那么我想将字典行复制到新字典 (Matches) 并从匹配的需求列表中添加 Dname,然后将其从供需列表(或将原始字典中的值设为 0)。

demand = [
{'id':1, 'Dname': 'A',  'val': 9},
{'id':2, 'Dname': 'B',  'val': 12},
{'id':3, 'Dname': 'C',  'val': 7},
 ];
 supply = [
 {'id':11, 'Sname': 's',  'val': 21},
 {'id':12, 'Sname': 't',  'val': 9},
  ];

我已经尝试过了,但它格式化了供应列表和新列表“匹配”。所以我不能让供应列表中的 val =0 并将其保持为新匹配列表中的原始值

Matches=[]
          for source in supply:
             for sink in demand:

          if source ['val'] == sink['val']:             #checking if there are any identical matches   
             Matches.append(source)                   #adding match (source) to matches list
            #Getting matches index to add sink to matches
            name_indexer = dict((p['Sname'], i) for i, p in enumerate(Matches))     
            index_no_matches=name_indexer.get(source['Sname']) 

            Matches[index_no_matches]['Dname'] = sink['Dname']  
            source['val']=0`

'''

谢谢!

标签: pythonlistdictionarycopyappend

解决方案


推荐阅读