[Python-Dev] Proposal: add odict to collections

Steven D'Aprano steve at pearwood.info
Sun Jun 15 10:44:13 CEST 2008

On Sun, 15 Jun 2008 05:12:38 pm Raymond Hettinger wrote:

> With an odict that preserves insertion order, you're talking about
> *deleting* the old entry and *appending* the new one, complete with
> both the new key and new value.

I certainly don't consider updating an ordered dictionary entry as a 
deletion followed by an append. In fact, I'd be very surprised, and 
dismayed, if that was the default behaviour.

Conceptually, I would expect the following behaviour:

>>> od = odict()
>>> od[1] = 'spam'  # insert a new key
>>> od[2] = 'parrot'  # insert a new key
>>> od[1] = 'ham'  # modify existing key
>>> od.items()
[(1, 'ham'), (2, 'parrot')]

If I wanted the alternative behaviour, I could easily get it:

>>> od = odict()
>>> od[1] = 'spam'  # insert a new key
>>> od[2] = 'parrot'  # insert a new key
>>> od.pop(1, None); od[1] = 'ham'  # remove and re-insert a key
>>> od.items()
[(2, 'parrot'), (1, 'ham')]

Earlier, Raymond also asked what to do about keys with equal but not 
identical keys. Since I consider setting the value to be an update 
rather than a deletion plus re-insertion, then the behaviour is 

>>> od = odict([(1, 'norwegian blue'), (2, 'parrot')])
>>> od[1.0] = 'norwegian red'
>>> od.items()
[(1, 'norwegian red'), (2, 'parrot')]

This is close to the behaviour of regular dicts, and to do differently 
would be very surprising to me. Again, anyone who wants the alternative 
behaviour can get it easily, with a pop and a set.

+1 for an ordered dictionary.

As for a sorted dictionary, I don't care much, so +0. You can always 
sort the keys when you need them.


More information about the Python-Dev mailing list