This issue tracker has been migrated to GitHub, and is currently read-only.
For more information, see the GitHub FAQs in the Python's Developer Guide.

classification
Title: Adding multiple keys of the same name to a dict doesn't raise an exception
Type: behavior Stage: resolved
Components: Versions: Python 3.11, Python 3.10, Python 3.9
process
Status: closed Resolution: not a bug
Dependencies: Superseder:
Assigned To: Nosy List: JelleZijlstra, shreyanavigyan, xtreak
Priority: normal Keywords:

Created on 2021-05-04 16:51 by shreyanavigyan, last changed 2022-04-11 14:59 by admin. This issue is now closed.

Messages (5)
msg392918 - (view) Author: Shreyan Avigyan (shreyanavigyan) * Date: 2021-05-04 16:51
Adding multiple keys of the same name to a dict should raise an exception but instead causes a different behavior. For example consider this code,

>>> d = {"x" : "First value", "x" : "Second value", "y" : "Third value"}

One would expect a error because there two keys with the same name or that Python will add "x" : "First value" and will skip "x" : "Second value". But the result is opposite,

>>> d
{'x': 'Second value', 'y': 'Third value'}

Is this a bug or is this an intended behavior? (I may have missed out information related to this in the documentation. Kindly correct me if that's the case.)
msg392925 - (view) Author: Karthikeyan Singaravelan (xtreak) * (Python committer) Date: 2021-05-04 17:26
Looks like a duplicate of https://bugs.python.org/issue16385
msg392927 - (view) Author: Shreyan Avigyan (shreyanavigyan) * Date: 2021-05-04 17:35
I've read that issue but it seems that it actually was based on "Should there be a warning or error?". I actually suggest something different. I suggest that "Either raise an exception or just use the first key-value pair if the key is repeated during initialization". (By "initialization" I mean to say creating a new dict object)
msg392937 - (view) Author: Jelle Zijlstra (JelleZijlstra) * (Python committer) Date: 2021-05-04 19:29
Looks like the same issue to me as the rejected issue that Karthikeyan mentioned. Changing it to use the first value is a non-starter because it would break compatibility. I'd suggest using a linter that warns about duplicate keys in literals; we implemented that internally.
msg392938 - (view) Author: Shreyan Avigyan (shreyanavigyan) * Date: 2021-05-04 19:36
Ok. I'm closing this then. (I wasn't aware that this was an intended behavior.)
History
Date User Action Args
2022-04-11 14:59:45adminsetgithub: 88199
2021-05-04 19:37:00shreyanavigyansetstatus: open -> closed
resolution: not a bug
stage: resolved
2021-05-04 19:36:44shreyanavigyansetmessages: + msg392938
2021-05-04 19:29:30JelleZijlstrasetnosy: + JelleZijlstra
messages: + msg392937
2021-05-04 17:35:45shreyanavigyansetmessages: + msg392927
2021-05-04 17:26:33xtreaksetnosy: + xtreak
messages: + msg392925
2021-05-04 16:51:35shreyanavigyancreate