[Python-Dev] PEP 372 -- Adding an ordered directory to collections ready for pronouncement

Steven D'Aprano steve at pearwood.info
Wed Mar 4 12:17:25 CET 2009


Gisle Aas wrote:

> Instead of introducing a sorteddict I would instead suggest that the 
> future should bring an odict with a sort method; possibly also 
> keys_sorted and items_sorted methods.

Instead of odict.sorted(), that can be spelled:

sorted(odict)  # sort the keys
sorted(odict.values())  # sort the items
sorted(odict.items())  # sort the (key, value) pairs

More complex variations are also possible.

The idea of a SortedDict is that it should be sorted at all times, 
without needing an explicit sort method, e.g.:

D = SortedDict(d=1, a=1, b=1)
print D
=> SortedDict(a=1, b=1, d=1)
D['c'] = 1
print D
=> SortedDict(a=1, b=1, c=1, d=1)

If you need to call a sort method on the dict to generate the sorted 
version, you might as well just pass the values you want to sorted(). 
That's more flexible, as you can sort whatever you want by anything you 
like.

I only know one use-case for a SortedDict: doctests. It's hard to use 
dicts in doctests, because when you print the dict, the items appear in 
arbitrary order. If you had a SortedDict, you could always predict what 
the dict would look like and use it in a doctest. Possibly there are 
other use-cases, but if so I don't know what they are.



-- 
Steven



More information about the Python-Dev mailing list