更新字典列表时遇到问题

时间:2021-03-08 17:13:26

标签: python python-3.x list function dictionary

我有一个简单的函数,它接收两个字典列表作为参数,并且应该比较列表 A 中的值是否在列表 B 中,然后更新列表 A 并返回更新后的列表 A。

我的函数有两个问题,首先,它没有更新列表 A 中的所有字典,它只是更新了两个,而不是三个。 user2 数据,有三个 dict 而不是两个。 其次,我想返回一个字典列表,而不是现在返回的多个字典。

这是我的功能:

    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'}]

请问这段代码有效吗?

请提供任何帮助或指导,我们将不胜感激。

谢谢

0 个答案:

没有答案