Dictionary sorting

Terry Reedy tjreedy at udel.edu
Thu Nov 3 17:36:25 EDT 2011


On 11/3/2011 2:46 PM, Scott Ware wrote:
> Python newbie here. So, when creating dictionaries, I am noticing
> that each time I print it out, that its not in the same order as when
> I typed it in. They seem to be getting sorted somehow.

No, the entries are not being sorted at all.

 > Is there a way to not sort them and leave the order as is?

CPython iterates (and prints) dict items in their arbitrary internal 
hash table order, which depends on the number and entry order of the 
items. It is a bug to depend on that arbitrary order in any way.

If you want to keep the dict sorted by entry order (as far as the user 
view goes), use collections.OrderedDict.

-- 
Terry Jan Reedy




More information about the Python-list mailing list