dict: keys() and values() order guaranteed to be same?

Steven D'Aprano steve+comp.lang.python at pearwood.info
Mon Jul 23 11:20:19 EDT 2012


On Mon, 23 Jul 2012 13:58:37 +0200, Stefan Behnel wrote:

> Philipp Hagemeister, 23.07.2012 13:40:
>> On 07/23/2012 01:23 PM, Henrik Faber wrote:
>>> With an arbitrary dictionaty d, are d.keys() and d.values() guaraneed
>>> to be in the same order?
>> 
>> Yes. From the documentation[1]:
>> 
>> If items(), keys(), values(), iteritems(), iterkeys(), and itervalues()
>> are called with no intervening modifications to the dictionary, the
>> lists will directly correspond.
>> 
>> [1] http://docs.python.org/library/stdtypes.html#dict.items
> 
> Interesting. I wonder if other implementations like Jython and PyPy
> really adhere to this official guarantee.

If they want to claim to be implementations of Python, as opposed to 
merely some Python-like language with identical syntax but different 
behaviour, then they better adhere to it. If they don't honour the 
language promise, then they are buggy.


[...]
> Maybe this guarantee is just easy enough to build on the given
> implementation details of a platform that it's a common property.

Easy or hard, it is a promise of the language.

(Although if you think about the implementation of dicts as hash tables, 
it does seem likely that it is trivial to enforce this -- one would have 
to work *harder* to break that promise than to keep it.)


> Iteration over data structures should tend to be deterministic, after
> all.

Deterministic is not a very strong promise. The order of iteration of 
dict.keys() is deterministic but not easily predictable, since it depends 
on the history of the dictionary. The output of random.random() is 
deterministic but (pseudo-)random.

Python's promise is much stronger than merely "deterministic": while it 
does not promise what order the keys will be returned, it does promise 
that whatever that order turns out to be, they will returned in the same 
order as the matching values (unless you modify the dict while iterating).



-- 
Steven



More information about the Python-list mailing list