0

I am learning dictionary which is a data type in Python.

A={'color':'right','color':'wrong'}
print(A)

In the above code, keys are the same. I expect it should be wrong since in my opinion key should be unique, but it prints out {'color': 'wrong'}, which confuses me a lot.

89085731
  • 141
  • 5
  • 1
    What's confusing about it? It's as you say, keys must be unique, so in this case, the dictionary will contain only one key-value pair (the latter). – Paul M. Jan 06 '21 at 22:00
  • @PaulM. I am expecting it will report wrong – 89085731 Jan 06 '21 at 22:01
  • 1
    you are right that dictionary contains unique keys. If you define the same key twice, second value overrides the first value of that key – Moinuddin Quadri Jan 06 '21 at 22:01
  • @PaulM. I don't know if Python guarantees to use the latter one, maybe it may choose any of those – Alexey S. Larionov Jan 06 '21 at 22:01
  • @89085731 If you want to print the value associated with the key `color`, you need to do `print(A["color"])`. – Paul M. Jan 06 '21 at 22:01
  • 3
    @AlexLarionov It is [guaranteed](https://docs.python.org/3/reference/expressions.html#dictionary-displays). – Paul M. Jan 06 '21 at 22:03
  • 1
    Don't confuse the dictionary display that creates a `dict` with the `dict` itself. A key can be repeated any number of times in the display, but the value in the resulting `dict` will be that of the rightmost occurrence of the key. – chepner Jan 06 '21 at 22:05
  • @buran thanks. That really works – 89085731 Jan 06 '21 at 22:08
  • @Alex Larionov: Python didn't always guarantee the use of the latter one, but at some point that changed (likely as a result of some PEP being implemented). – martineau Jan 06 '21 at 22:13

1 Answers1

2

dict keys must be unique. If you reassign a key, the dictionary just deletes the existing entry before adding the new value.

>>> A = {'color':'right'}
>>> A
{'color': 'right'}
>>> A['color'] = 'wrong'
>>> A
{'color': 'wrong'}

That's what happened in your case

A={'color':'right','color':'wrong'}

The 'color', 'right' key/value pair was set but it was deleted when the like keyed 'color', 'wrong' pair was set afterwords. The same thing happens if you use the dict constructor

>>> A = dict([('color', 'right'), ('color', 'wrong')])
>>> A
{'color': 'wrong'}
tdelaney
  • 73,364
  • 6
  • 83
  • 116