"Ordered" dicts

Chris Cioffi evenprimes at gmail.com
Wed Aug 10 08:35:49 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. It's in the FAQ (
http://www.python.org/doc/faq/programming.html#how-can-i-get-a-dictionary-to-display-its-keys-in-a-consistent-order)
and has recently shown up as a recipe (
http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/438823).
 I have lots of code that looks like:
 keys = mydict.keys()
 keys.sort()
 It seems that there should be a more straight foreward way to address this 
extremely common use case. How about adding optional parameters to some of 
the dict methods that control the order that keys are returned?
 For example, instead of the above lines, maybe make it:
 keys = mydict.keys(sorted=True)
 .items() could work the same way. It could probably work for .iterkeys() 
and .iteritems() as well, though the trivial implementation wouldn't save 
any memory over .keys(). 
 Maybe we could even extend it to:
 keys = mydict.keys(sorted=True, reversed=True) # of something...
 It just seems that the community spends a lot of time working around this 
issue and there is a simple solution. (For a given definition of simple :) 
 The pros:
-Simple syntax that is fully backward compatible
-Seems like it would save a lot of effort in education and meet a community 
need
-Dicts are by definition unordered, "Although practicality beats purity."
 The cons:
-May be difficult to implement the .iter*() methods efficiently. 
 What do y'all think?
 Chris
-- 
"Obviously crime pays, or there'd be no crime." -- G. Gorden Liddy
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-list/attachments/20050810/00fd8ca9/attachment.html>


More information about the Python-list mailing list