首页 > 解决方案 > dict列表中的值总和错误

问题描述

从带有字典列表的 JSON 文件中,我试图获取每个用户的数据并使用它们来创建新的字典。由于每个用户都有多个对象,因此我使用 for 循环通过它们进行交互。开始 json 看起来像这样:

[{
  "obj_id": "bfyguwc9971",
  "user_id": 3,
  "investment": 34,
  "profit": 67
},
{
  "obj_id": "sdklgnv820",
  "user_id": 12,
  "investment": 71,
  "profit": 43
}]

JSON 包含数百个这样的字典,我想要实现的是最终的字典,其中包含每个用户的平均投资和利润。这是我正在运行的代码:

import json
with open('user_data.json','r') as f:
    user_data = json.load(f)

users_id = []
users_dict = {}
obj_count = 0
investment_list = []
profit_list = []

for i in user_data:
    if i['user_id'] not in users_id:
        users_id.append(i['user_id'])

for a in users_id:
    users_dict[a] = {}
    for i in user_data:
        if i['user_id'] == a:
            obj_count += 1
            users_dict[a]['Objects'] = obj_count
            investment_list.append(i['investment'])
            profit_list.append(i['profit'])
    avg_investment = (sum(investment_list)/len(investment_list))
    users_dict[a]['avg_investment'] = avg_investment
    avg_profit = (sum(profit_list)/len(profit_list))
    users_dict[a]['avg_profit'] = avg_profit
print(users_dict)

问题出现在输出中,而不是给我每个用户正确的单个值,它给了我第一个用户值的权利,然后它继续为下一个用户添加值,所以最后一个用户将拥有所有以前的值为其他用户计算。我究竟做错了什么?提前感谢您帮助我!

标签: pythonjsonlistdictionaryappend

解决方案


推荐阅读