Home > Enterprise >  Why is the value not getting added to the dictionary value?
Why is the value not getting added to the dictionary value?

Time:12-29

capacity =  [10,2,2]
rocks = [2,2,0]
a=100
bags= {c:r for (c,r) in zip(capacity,rocks)}
print(bags)


'''
{10: 2, 2: 0}
'''

I want to get {10: 2, 2:2, 2: 0} but instead I am getting {10: 2, 2: 0}

CodePudding user response:

As @Pranav Hosangadi commented, you cannot have duplicate keys in dictionaries.

Assigning a value to a key that already exists will overwrite the existing value. This is what your dictionary comprehension is doing. The key "2" already exists (created in the second iteration) so it is assigned the value 0 by the last iteration. Ergo you end up with two elements in your dictionary instead of the three you were expecting.

  • Related