-1

I read this in the official documentation of Python

It is best to think of a dictionary as a set of key: value pairs, with the requirement that the keys are unique (within one dictionary).

But when I am running this code

dic={"a":1,"b":2,"a":3,"a":2,"a":4,"a":5}
print(dic["a"])

I'm always getting 5 as output. I want to know why.

jonrsharpe
  • 115,751
  • 26
  • 228
  • 437
EXODIA
  • 908
  • 3
  • 10
  • 28
  • Just a guess: It evaluates the pairs in sequence, so you're constantly overwriting "a"'s value – Mars Apr 26 '19 at 07:21
  • And this does not contradict with that documentation: the dict is required to keep only unique keys, so it decides to keep the last pair only – Andrii Maletskyi Apr 26 '19 at 07:22

2 Answers2

2

If you have a dict literal (within {}) and a key occurs multiple times, the last one "overwrites" the previous ones. It's just the decision that was taken in the first versions of Python.

Print the whole dict to see:

>>> dic={"a":1,"b":2,"a":3,"a":2,"a":4,"a":5}
>>> dic
{'a': 5, 'b': 2}

See the docs, emphasis mine:

If a comma-separated sequence of key/datum pairs is given, they are evaluated from left to right to define the entries of the dictionary: each key object is used as a key into the dictionary to store the corresponding datum. This means that you can specify the same key multiple times in the key/datum list, and the final dictionary’s value for that key will be the last one given.

RemcoGerlich
  • 30,470
  • 6
  • 61
  • 79
1

You just answered it in your quote from documentation - keys are unique, so "a" keeps getting re-assigned - and holds only last value - that's 5 in your case

Drako
  • 773
  • 10
  • 22