"Ordered" dicts

mekstran at scl.ameslab.gov mekstran at scl.ameslab.gov
Wed Aug 10 08:52:30 EDT 2005


> Lots and lots of people want ordered dicts it seems. Or at least, they
> want
> to be able to access their dictionary keys in order.
> [snipped lots of examples, nice pro-con lists, etc.]
>  What do y'all think?

I'll second the need for this. Although, what can also be useful as a
further extension (at least I needed this capability for a project I
worked on) is the ability to not only have the keys sorted, but have them
arranged in an arbitrary order (I had parsed some XML data, and each
"object" represented in the XML had certain fields, which I was storing in
a dictionary, but I needed each object to iterate that dictionary in the
same order, preferably the order they occured in the file).

I accomplished this through subclassing dict to create a
SpecialSortedDict, overriding keys(), values(), the iterxxx() functions,
and any others relevant so that it had an associated key order list. It
would return keys in the specified order (ignoring any in the order list
that weren't in the dictionary), an then any remaing keys were sorted at
the end.

I don't know if that'd be a useful enhancement to Chris's idea, or if it's
a really obscure corner case. But I thought I'd throw it out there.




More information about the Python-list mailing list