Easiest way to update dictionary values from a list?

Question:

Here is my original dictionary:

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

I want to change the values of Maths, Physics and Chemistry from a list:

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

I want my dictionary to look like this after changing values of my dictionary from a list:

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

Can anybody help me to automatically update dictionary values from a list in Python?

Asked By: Lakshmi Vallabh

||

Answers:

Try something like this:

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)

Output:

{'Teachers': {'Maths': 'Alex', 'Physics': 'Rahul', 'Chemistry': 'Micheal'}}
Answered By: funnydman
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.