[Python-ideas] dict literal allows duplicate keys

Jonathan Fine jfine2358 at gmail.com
Wed Mar 6 11:58:30 EST 2019


SUMMARY: The outcome of a search for: python dict literal duplicate
keys. No conclusions (so far).

BACKGROUND
In the thread  "PEP: Dict addition and subtraction" I wrote

>     >>>  {'a': 0, 'a': 1}
>     {'a': 1}

> I wonder, is this behaviour of {'a': 0, 'a': 1} documented (or tested)
> anywhere? I didn't find it in these URLs:
> https://docs.python.org/3/library/stdtypes.html#mapping-types-dict
> https://docs.python.org/3/tutorial/datastructures.html#dictionaries

LINKS
I've since found some relevant URLs.

[1] https://stackoverflow.com/questions/34539772/is-a-dict-literal-containing-repeated-keys-well-defined
[2] https://help.semmle.com/wiki/display/PYTHON/Duplicate+key+in+dict+literal
[3] https://bugs.python.org/issue26910
[4] https://bugs.python.org/issue16385
[5] https://realpython.com/python-dicts/

ANALYSIS
[1] gives a reference to [6], which correctly states the behaviour of
{'a':0, 'a':1}, although without giving an example. (Aside: Sometimes
one example is worth 50 or more words.)

[2] is from Semmle, who provide an automated code review tool, called
LGTM. The page [2] appears to be part of the documentation for LGTM.
This page provides a useful link to [7].

[3] is a re-opening of [4]. It was rapidly closed by David Murray, who
recommended reopening the discussion on python-ideas.
[4] was raised by Albert Ferras, based on his real-world experience.
In particular, a configuration file that contains a long dict literal.
This was closed by Benjamin Peterson, who said that raising an error
was "out of the question for compatibility isssues". Given few use
case and little support on python-ideas,Terry Ready supported the
closure. Raymond Hettinger supported the closure.

[5] is from RealPython, who provide online tutorials. This page
contains the statement "a given key can appear in a dictionary only
once. Duplicate keys are not allowed." Note that
    {'a': 0, 'a': 1}
can reasonably be thought of as a dictionary with duplicate keys.

NOTE
As I recall SGML (this shows my age) allows multiple entity declarations, as in
    <!ENTITY key "original">
    <!ENTITY key "updated">

And as I recall, in SGML the first value "original" is the one that is
in effect. This is what happens with the LaTeX command
\providecommand.

FURTHER LINKS
[6] https://docs.python.org/3/reference/expressions.html#dictionary-displays
[7] https://cwe.mitre.org/data/definitions/561.html # CWE-561: Dead Code

-- 
Jonathan


More information about the Python-ideas mailing list