[Python-ideas] dictionary constructor should not allow duplicate keys

Akira Li 4kir4.1i at gmail.com
Wed May 4 16:34:48 EDT 2016


Steven D'Aprano <steve at pearwood.info> writes:

> How do dict displays construct the dict? Do they add keys from left to
> right, or right to left? I can read the source, if I can find it, and
> locate the right section of the right file, and if I can read C. Or I
> can do:
>
> py> {1: "left", 1: "right"}
> {1: 'right'}
>
> and in one line of code in the Python interactive interpreter I've
> learned more than in probably an hour of digging through C code.

The language reference explicitly says that the order from left to right
and duplicate keys are also explicitly supported [1]:

  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.

[1] https://docs.python.org/3/reference/expressions.html#dictionary-displays


Akira



More information about the Python-ideas mailing list