Order of tuples in dict.items()

Erik Jones erik at myemma.com
Mon Oct 15 10:47:06 EDT 2007


On Oct 14, 2007, at 5:27 PM, Steven D'Aprano wrote:

> On Sun, 14 Oct 2007 13:26:27 -0700, Erik Max Francis wrote:
>
>> 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?
> [...]
>>> Can I rely on this behavior?
>>
>> Probably not.
>
> Definitely not. See Paul Hankin's earlier post in this thread.
>
>
>> 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.
>
> Well, I suppose it *is* possible for Python to change its hash  
> function
> in some future version, but Python hashing is highly optimized,  
> very fast
> and not likely to change.
>
> It's especially not likely to change in the middle of a run of your
> program, say between calling a.items() and calling b.items().

Not between two consecutive reads, no.  However, after any resizing  
of a dict the result of Python's hash function for any given newly  
inserted key is extremely likely to be different than it would have  
been before the resizing, i.e. the method may be the same, but the  
result is different.

Erik Jones

Software Developer | Emma®
erik at myemma.com
800.595.4401 or 615.292.5888
615.292.0777 (fax)

Emma helps organizations everywhere communicate & market in style.
Visit us online at http://www.myemma.com





More information about the Python-list mailing list