-2

If I create a dictionary with two of the same key, as shown below with name being there twice:

test = {'name': 'hello', 'test': 'rawr', 'next': 'muhahah', 'name': None, 'la': 'alala'}

How does python behave with this setup, does it keep both keys, or just one? And will it always return a certain one if I do test['name']?

With my own testing it returns the second one, just looking for some more information.

geckon
  • 8,316
  • 4
  • 35
  • 59
nazerb
  • 319
  • 1
  • 2
  • 11
  • 2
    When you copy/paste that line into the interpreter - what do you get? That pretty much answers your question. – Jon Clements Aug 07 '15 at 10:09
  • You cannot have duplicate keys in dictionary , when you try to set value for a key that already exists in the dictionary, it overwrites previous value. – Anand S Kumar Aug 07 '15 at 10:09
  • @Jon Clements It returns the second one, however I was just looking for some more information what happens 'under the hood'. – nazerb Aug 07 '15 at 10:09
  • Dictionaries can only map *unique keys* to values, that's the definition of a mapping. From the [*Mapping types - `dict`* documentation](https://docs.python.org/2/library/stdtypes.html#mapping-types-dict): *If a key occurs more than once, the last value for that key becomes the corresponding value in the new dictionary.* – Martijn Pieters Aug 07 '15 at 10:10
  • @nazerb: can you please edit your question then to show what kind of information you are looking for? There are numerous other posts here on Stack Overflow that detail how the Python dictionary implementation works, for example. See [How are Python's Built In Dictionaries Implemented](http://stackoverflow.com/q/327311) and [Why is the order in Python dictionaries and sets arbitrary?](http://stackoverflow.com/q/15479928) for example. – Martijn Pieters Aug 07 '15 at 10:19
  • More documentation, from the [*Dictionary displays* (literal syntax) page](https://docs.python.org/2/reference/expressions.html#dictionary-displays): *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.* – Martijn Pieters Aug 07 '15 at 10:22

1 Answers1

2

By definition, displays (the literal syntax for lists, dicts and sets) are evaluated from left to right; see https://docs.python.org/2/reference/expressions.html#displays-for-sets-and-dictionaries

That means that for a dict literal like your example, the last value always "wins". (And keys are unique, so you can't ever have more than one value.)

wouter bolsterlee
  • 3,879
  • 22
  • 30