首页 > 解决方案 > 根据条件更新python dict值?

问题描述

我的字典如下

user_model = {
    "users": [{
            "userid": 100,
            "level": 1,
            "score": 5,
        },
        {
            "userid": 101,
            "level": 2,
            "score": 5,
        },
        {
            "userid": 100,
            "level": 2,
            "score": 5,
        },
        {
            "userid": 103,
            "level": 1,
            "score": 2,
        }
    ]
}

如果我的“用户 ID”为 103 且“级别”为 2,有人可以指点我正确的方向以仅更新“分数”。

谢谢

标签: pythonpython-3.xdictionary

解决方案


这样您就可以列出 json 中的所有数据:

for item in user_model['users']:
    print(item) #check items
    if item['userid'] == 103:
        item['score'] = 25
        print(item)

推荐阅读