python - 更新字典列表时遇到问题
问题描述
我有一个简单的函数,它接收两个字典列表作为参数,并且应该比较列表 A 中的值是否在列表 B 中,然后更新列表 A 并返回更新的列表 A。
我的函数有两个问题,首先,它没有更新列表 A 中的所有字典,它只是更新了两个,而不是三个。user2 数据,有三个字典而不是两个。其次,我想返回一个字典列表,而不是现在返回的多个字典。
这是我的功能:
from itertools import zip_longest
def test(user, model):
for d1, d2 in list(zip_longest(user, model,
fillvalue={
"asset": "No Fund",
"amount": 0
}
)):
model_assets = d2["assets"]
user_assets = d1["asset"]
if any(user_assets in s for s in model_assets):
d1.update({"rating": d2["rating"]})
print(d1)
test(user2, inv_class)
output --->
{'asset': 'Money Market Fund', 'amount': 100000, 'rating': 'Low-2'}
{'asset': 'Easy Will', 'amount': 40000, 'rating': 'Moderate'}
数据:
inv_class = [
{
"rating": "Low-1",
"score": "2-3",
"type": "Capital Preservation",
"assets": [
"Money Market Fund",
"Treasury Bills",
"Easy Will",
"Education Trust"
]
},
{
"rating": "Low-2",
"score": "4-5",
"type": "Income",
"assets": [
"Money Market Fund",
"FGN Retail Savings/FGN Corporate Bonds",
"Easy Will",
"Education Trust"
]
},
{
"rating": "Moderate",
"score": "6-7",
"type": "Income & Growth",
"assets": [
"Euro-bond Fund",
"Fixed Income Fund",
"Ethical Fund",
"Easy Will",
"Education Trust"
]
},
{
"rating": "High",
"score": "8",
"type": "Growth",
"assets": [
"Discovery Fund",
"Ethical Fund",
"Local Stocks",
"Foreign Stocks",
"Easy Will",
"Education Trust"
]
},
{
"rating": "Very High",
"score": "9",
"type": "Aggressive Growth",
"assets": [
"Aggressive Growth Fund",
"Local Stocks",
"Foreign Stocks",
"Easy Will",
"Education Trust"
]
}
]
用户数据:
user2 = [
{
"asset": "Fixed Income Fund",
"amount": 150000
},
{
"asset": "Money Market Fund",
"amount": 100000
},
{
"asset": "Easy Will",
"amount": 40000
}
]
更新功能:
def test3(user, model):
result = []
for u in user:
y = u["asset"]
for items in model:
ind = items["assets"]
for i in ind:
if i in y:
u["rating"] = items["rating"]
result.append(u)
return result
输出:
test3(user1, inv_class)
[{'asset': 'Discovery Fund', 'amount': 100000, 'rating': 'High'},
{'asset': 'Ethical Fund', 'amount': 200000, 'rating': 'High'},
{'asset': 'Foreign Stocks', 'amount': 350000, 'rating': 'Very High'},
{'asset': 'Local Stocks', 'amount': 550000, 'rating': 'Very High'}]
请问这段代码有效吗?
请任何帮助或指导将不胜感激。
谢谢
解决方案
推荐阅读
- python - 在python中将opencv图像写入zip文件
- java - 如何从 InnerClass 访问 OuterClass 字段?
- python - 从python字典中获取值并一一传递
- html - 菜单上的 Css 菜单动画仅在初始页面加载时有效,如果我返回菜单页面则失败
- python - 从 GroupBy 打印一个有组织的 DataFrame
- arrays - 将预加载的值保存在内存中 - Swift/SwiftUI
- r - 如何编写循环来运行数据帧的 Mann whitney U 测试?
- php - 通过按下刀片视图上的按钮但不刷新页面来更新 Laravel 中的用户属性调用控制器上的函数
- javascript - 获取深度嵌套的 HTML 元素标题的递归函数返回未定义
- java - java中的扫描问题