[Python-Dev] The current dict is not an "OrderedDict"

Chris Angelico rosuav at gmail.com
Tue Nov 7 14:19:46 EST 2017


On Wed, Nov 8, 2017 at 1:32 AM, Antoine Pitrou <solipsis at pitrou.net> wrote:
> On Wed, 8 Nov 2017 00:01:04 +1000
> Nick Coghlan <ncoghlan at gmail.com> wrote:
>
>> On 7 November 2017 at 23:48, Stefan Krah <stefan at bytereef.org> wrote:
>> >
>> >
>> > This is just a reminder that the current dict is not an "OrderedDict":
>> >
>> >>>> from collections import OrderedDict
>> >>>> OrderedDict(a=0, b=1) == OrderedDict(b=1, a=0)
>> > False
>> >>>> dict(a=0, b=1) == dict(b=1, a=0)
>> > True
>> >
>> > The recent proposal was primarily about guaranteeing the insertion order of
>> > dict literals.
>> >
>> > If further guarantees are proposed, perhaps it would be a good idea to
>> > open a new thread and state what exactly is being proposed.
>>
>> "Insertion ordered until the first key removal" is the only guarantee
>> that's being proposed.
>
> Is it?  It seems to me that many arguments being made are only relevant
> under the hypothesis that insertion is ordered even after the first key
> removal.  For example the user-friendliness argument, for I don't
> think it's very user-friendly to have a guarantee that disappears
> forever on the first __del__.

I've used a good few dictionary objects in my time, but most of them
have literally never had any items deleted from them. Consider a
simple anagram finder:

anagrams = defaultdict(list)
for word in words:
    anagrams[''.join(sorted(word))].append(word)
for words in anagrams.values():
    if len(words) > 5:
        print(words)

New items get added to the dictionary, but nothing is ever removed. I
can assume, with CPython's current semantics, that the final iteration
will be in order of first seen; whatever order the incoming word list
was in, the output will be in too. This IS a useful guarantee, even
with the caveats.

ChrisA


More information about the Python-Dev mailing list