6. Using the Same Key Multiple Times

Screen Link:

My Code:

keys   = [1, 2, 1, 3, 1, 4]
values = [1, 2, 3, 4, 5, 6]
d = {}
for i in range(len(keys)):
    d[keys[i]] = values[i]
    
"""
d[1] gets updated three times.
The first time it gets value 1
The second time it gets value 3
The third time it gets value 5
"""
answer = 5

WHY does d[1] get updated 3 times??? My understanding is, for each i in the range of 6, assign the ith value to the ith key. First iteration, keys[0]:values[0] = 1:1, 2nd iteration keys[1]:values[1] = 2:2, 3rd iteration, 1:3… why does 1:3 overwrite 1:1 and not just add 1:3 as a new key-value pair in the dictionary?

The keys are unique in dictionary. We can not add same keys multiple time.

Hence, at the 3rd time iteration (1:3) we had already key 1 in dictionary so it overwrite value of 1.

1 Like