Please tell me what I am doing wrong!
I wish to update entries in a dictionary from a list. Here are my (simplified) dictionary and list:
scene_dict = {0: {'speaker': None, 'listener': None}, 1: {'speaker': None, 'listener': None}}
speaker_list = ["Horatio", "Marcellus"]
I want to achieve the following result:
scene_dict = {0: {'speaker': "Horatio", 'listener': None}, 1: {'speaker': "Marcellus", 'listener': None}}
which would seem to be a straight-forward problem.
In order to achieve the required result, I do the following:
for i, j in enumerate(scene_dict):
scene_dict[j]["speaker"] = speaker_list[i]
which then gives the result I want, yeh!
print(scene_dict)
{0: {'speaker': 'Horatio', 'listener': None}, 1: {'speaker': 'Marcellus', 'listener': None}}
So, "where's the problem?" you may ask. Well, in reality, the list of names that I am dealing with is much longer. So, my dictionary needs to be correspondingly much longer, but it has the exact same form. Naturally, I don't want to define my dictionary by writing it down explicitly. I need to generate it somehow, which I do as follows:
para_dict = {"speaker": None, "listener": None}
scene_dict = {}
for k in range(0,2):
scene_dict[k] = para_dict
This "appears" to work fine, and "appears" to give the exact same dictionary as I started with:
print(scene_dict)
{0: {'speaker': None, 'listener': None}, 1: {'speaker': None, 'listener': None}}
However, when I now re-run the exact same for loop above on my ("exact same") generated dictionary, in order to transfer the elements of my list to the values in the dictionary
for i, j in enumerate(scene_dict):
scene_dict[j]["speaker"] = speaker_list[i]
I get a different (wrong) result:
print(scene_dict)
{0: {'speaker': 'Marcellus', 'listener': None}, 1: {'speaker': 'Marcellus', 'listener': None}}
This time the for loop apparently equates both dictionary keys ("speaker") at the same time with the first name in the list, and then both keys with the second name in the list, i.e. it equates both with Horatio and then both with Marcellus.
I am mystified. What did I do wrong? How can I do better?
Any advice would be appreciated.