Order of tuples in dict.items()

Erik Max Francis max at alcyone.com
Sun Oct 14 16:26:27 EDT 2007


Will McGugan wrote:

> If I have two dictionaries containing identical values, can I be sure 
> that the items() method will return tuples in the same order?
> 
> I tried an experiment with CPython and it does appear to be the case.
> 
>  >>> a=dict(a=1, b=1, c=2)
>  >>> b=dict(c=2, a=1, b=1)
>  >>> a
> {'a': 1, 'c': 2, 'b': 1}
>  >>> b
> {'a': 1, 'c': 2, 'b': 1}
>  >>> a.items()
> [('a', 1), ('c', 2), ('b', 1)]
>  >>> b.items()
> [('a', 1), ('c', 2), ('b', 1)]
> 
> Can I rely on this behavior?

Probably not.  Dictionaries do not have an ordering that you should 
count on.  In practice, the order in which you get the items if you 
iterate over a dictionary is dependent on the hashing function, which 
can potentially change over time.

This is a case where most implementations _probably_ will return 
identical dictionaries in the same order when iterated over (of course, 
different implementations will have different orderings, but you don't 
care about that), but I wouldn't take the chance and rely on such an 
implementation detail.

If you want to keep track of the order in which objects were added to a 
dictionary, you'll need to keep a separate list of (sorted) keys, which 
is easy enough.  If you're lazy there are plenty of recipes around for 
things like `SortedDictionary` or `sorteddict`.

-- 
Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/
  San Jose, CA, USA && 37 20 N 121 53 W && AIM, Y!M erikmaxfrancis
   The public cannot be too curious concerning the characters of public
    men. -- Samuel Adams



More information about the Python-list mailing list