从列表中更新字典值的最简单方法?

bweufnob  于 2022-10-02  发布在  Python
关注(0)|答案(1)|浏览(147)

这是我的原版词典:

original_dict = {
    "Teachers": {
        "Maths": "Kiran",
        "Physics": "David",
        "Chemistry": "Ravi"
    }
}

我想从列表中更改数学、物理和化学的值:

my_new_values_list = ["Alex", "Rahul", "Micheal"]

我希望我的词典在从列表中更改词典的值后看起来是这样的:

{
    "Teachers": {
        "Maths": "Alex",
        "Physics": "Rahul",
        "Chemistry": "Micheal"
        }
    }

有没有人能帮我从一个列表中自动更新字典值?

mrfwxfqh

mrfwxfqh1#

试着这样做:

original_dict = {
    "Teachers": {
        "Maths": "Kiran",
        "Physics": "David",
        "Chemistry": "Ravi"
    }
}

my_new_values_list = ["Alex", "Rahul", "Micheal"]
original_dict['Teachers'] = dict(zip(original_dict['Teachers'].keys(), my_new_values_list))

print(original_dict)

产出:

{'Teachers': {'Maths': 'Alex', 'Physics': 'Rahul', 'Chemistry': 'Micheal'}}

相关问题