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

M.-A. Lemburg mal at egenix.com
Wed May 4 07:56:56 EDT 2016

On 04.05.2016 03:09, Steven D'Aprano wrote:
> On Mon, May 02, 2016 at 02:36:35PM -0700, Luigi Semenzato wrote:
>> The original problem description:
>> lives_in = { 'lion': ['Africa', 'America'],
>>              'parrot': ['Europe'],
>>              #... 100+ more rows here
>>              'lion': ['Europe'],
>>              #... 100+ more rows here
>>            }
>> The above constructor overwrites the first 'lion' entry silently,
>> often causing unexpected behavior.

Issuing a warning for this would probably help, but raising
an error introduced a backwards incompatibility which is
not warranted IMO, given how seldom such situations occur in

For the implementation, there are two possibilities I can think

1. have STORE_MAP run a test for an already existing entry
   and issue a warning

2. add a final CHECK_MAP byte code to check that the number
   of keys in the mapping correspond to the number of keys
   added via the dict literal

The first one causes a lot of overhead, esp. for larger mappings
such as the ones used by the codecs or other static data tables.
Most of the times these are generated anyway, so the warning
case would not occur at all, but you'd still have to check
for a collision N times.

The second one is cheap regarding performance, but may not
be accurate, since STORE_MAP may well be working on dynamically
generated keys. It does work well for constants, and if we're
just issuing a warning, may be good enough.

Marc-Andre Lemburg

Professional Python Services directly from the Experts (#1, May 04 2016)
>>> Python Projects, Coaching and Consulting ...  http://www.egenix.com/
>>> Python Database Interfaces ...           http://products.egenix.com/
>>> Plone/Zope Database Interfaces ...           http://zope.egenix.com/

::: We implement business ideas - efficiently in both time and costs :::

   eGenix.com Software, Skills and Services GmbH  Pastor-Loeh-Str.48
    D-40764 Langenfeld, Germany. CEO Dipl.-Math. Marc-Andre Lemburg
           Registered at Amtsgericht Duesseldorf: HRB 46611

More information about the Python-ideas mailing list