Dictionaries Mission Practice Problems Q5

Screen Link:

My Code:

keys = ['Katherine Freeman', 'Tammy Gonzalez', 'Robin Matthews', 'Sherry Farrell', 'Emma Graves', 'Tina Brown', 'George Owens', 'Ronald Ball']
values = ['[email protected]', '[email protected]', '[email protected]', '[email protected]', '[email protected]', '[email protected]', '[email protected]', '[email protected]']

my_dict = {}
for i in range(len(keys)):
    my_dict[keys[i]] = values[i]

What I expected to happen:

What actually happened:

Replace this line with the output/error

I know if i do my_dict[keys] ill be accessing the values of the dictionary. So in “practical terms” I would be saying: “assign to the values of my_dict " the elements of the values list”. Why do I need the [i] in my_dict[keys[i]]?

Hi @AntnioSDaCunha,

If you have 2 lists of the same lengths (one for the keys, second for the values), you can create a dictionary without using the for-loop:

my_dict = dict(zip(keys,values))

Yes, I can see that in the alternative answers. Im just trying to grasp the logic behind the code using the for loop

Using the for-loop, you are practipally “zipping” them manually. With each iteration, you take the i-th item of the keys list (i.e. keys[i]), assign it as a key of your (initially empty) dictionary, and then assign to that new key the value, which is the i-th item of the values list (i.e. values[i]).

2 Likes

@ AntnioSDaCunha Antnio S Da No you can’t use my_dict[keys], because keys is a list and any list or dictionary can’t be a key of a dictionary. You have two list of same length.So, you are looping through their positions by a for loop with an index variable “i” and the range is length of list “keys”(or you can use values too, since the length is same).
Now your my_dict[keys[i]] = values[i] is working as follows,
values[i] = values[0]= 1st email
And so on…
keys[i] = keys[0] = 1st name
my_dict[1st name] = 1st email and so on…
Therefore my_dict = {1st name : 1st email, and so on…}.
Hope it will help you.

1 Like

Hey what if the two list arent of the same length? I understood the logic behind the original question, you explained it very well. Thanks for your help.