python - 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`
'''
谢谢!
解决方案
推荐阅读
- swift - 在核心数据中存储一个 UImage 数组
- node.js - 调试 AWS Lambda node.js ES6
- java - Eclipse/Java 出现奇怪的零星(空格?)错误?
- class - 飞镖类中的初始值
- angular - Angular 和 Laravel - 根据登录名和用户 ID 显示并保存到数据库中
- laravel - 使用外键 Laravel 更新表单
- javascript - 我需要导入脚本来在 react JS 中创建 JS 类
- python - 如何使用 pathlib 规范化相对路径
- dll - 如何修复 Unity 中的“UnityEngine.UI.dll 不允许包含或不能包含”?
- r - 如何在 GAM (mgcv) 中对调查数据使用样本权重进行 Logit 回归?