Why are there no ordered dictionaries?

Bengt Richter bokr at oz.net
Tue Nov 22 23:00:57 CET 2005

On Tue, 22 Nov 2005 20:15:18 +0100, Christoph Zwerschke <cito at online.de> wrote:

> >>def __init__(self, init_val = ()):
> >>     dict.__init__(self, init_val)
> >>     self.sequence = [x[0] for x in init_val]
>Fuzzyman wrote:
> > But that doesn't allow you to create an ordered dict from another
> > ordered dict.
>Right; I did not want to present a full implementation, just the 
>relevant part. Of course, a real implementation should also allow to 
>build an ordered dict from another ordered dict or an ordinary dict. (In 
>the latter case, maybe the keys should be automatically sorted.) But one 
>or two case disctinctions would not make things mentionable slower.
Since the OrderedDict constructor takes a sequence of tuples as a legitimate
argument, you can always create an ordered dict from an unordered by getting
unordered_dict.items() and sorting or ordering them any way you want and calling
the OrderedDict constructor. Ditto for ordered dicts, since they give your their
ordered items with the items() method as a start. I guess one could pass a
key=fun keyword arg to the OrderedDict constuctor to imply a pre-construction sort.

Bengt Richter

More information about the Python-list mailing list