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

Ethan Furman ethan at stoneleaf.us
Tue May 3 17:27:16 EDT 2016

On 05/03/2016 01:43 PM, Michael Selik wrote:
> On Tue, May 3, 2016 at 4:00 PM Ethan Furman wrote:

>> Which seems irrelevant to your argument: a duplicate key is a duplicate
>> key whether it's 123 or 'xyz'.
> If an expression includes an impure function, then the duplication of
> assignment to that key may have a desirable side-effect.

I'm willing to say that should be done with an existing dict, not in a 

>> I'm pretty sure the OP would be happy with uniqueness of keys, whether
>> those keys were string literals, numeric literals, or function objects.
> How would you handle an expression that evaluates differently for each
> call? For example:
>      {random(): 0, random(): 1}

Easy:  Don't Do That.  ;)

> Let me flip the original request: I'd like to hear stronger arguments for
 > change, please. I'd be particularly interested in hearing how often 
 > has caught this mistake.

Well, when this happened to me I spent a loooonnnnnngggg time figuring 
out what the problem is.  One just doesn't expect duplicate keys to not 

--> dict(one=1, one='uno')
   File "<stdin>", line 1
SyntaxError: keyword argument repeated

So I guess the current advice is:  Don't use dict literals, use dict() 
instead.  And that just seems silly.  ;)


More information about the Python-ideas mailing list