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

Luigi Semenzato luigi at semenzato.com
Tue May 3 12:47:07 EDT 2016

I am still not seeing good objections to not adding at least a warning.

>> On Tue, May 3, 2016 at 12:06 AM Michel Desmoulin
>> <desmoulinmichel at gmail.com <mailto:desmoulinmichel at gmail.com>> wrote:
>>     With Python 3.5, you can unpack in dictionaries:
>>     d = {**foo, **bar}

and similarly:

> foo = 1
> bar = "1"
> {1: True, 2 - 1: True, foo: True, int(bar): True, int("1"): True, **{1:
> True}}
> But not this:
> {1: True, 1: True}

Probably I didn't make it sufficiently clear in my OP, but this is
only for duplicate literal keys in the same constructor, which would
cover the vast majority of user errors.

A well-known precedent is the divide-by-zero warning in C.  The GNU
compiler produces a warning when, after constant folding, an
expression contains a division by zero.  For instance:

test.c:9:12: warning: division by zero [-Wdiv-by-zero]
   int z = 1/0;

and this:

test.c:9:12: warning: division by zero [-Wdiv-by-zero]
   int z = 1/(1 - 1);

but this code doesn't produce a warning:

  const int x = 0;
  int z = 1/x;

For the dict constructor, I don't think that the constant folding is
even particularly useful, although it wouldn't hurt.

Implementation-wise, checking for duplicate literals while parsing is
just a matter of maintaining a hash table for that scope.  This is
already done for identifiers, and probably heavily optimized, so
duplicate detection wouldn't add much code or be particularly

More information about the Python-ideas mailing list