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

Henrik Faber hfaber at invalid.net
Mon Jul 23 14:19:30 CEST 2012

On 23.07.2012 13:40, Philipp Hagemeister wrote:
> 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.

Ah, nice!

> In most cases, you should simply use items() though. Can you elaborate
> on the use case for needing both keys() and values(), where items() is
> not applicable?

I need to parse and modify the keys of the dict and pass the keys as a
compound object to a function, which expects the values to be passed as
an argument list (weird, but can't change that). The order of arguments
is arbitrary (as the iteration over a dict is), but there has to be a
1-to-1 relation bewtween the compound object's key order and the
argument list's value order.

Best regards,

More information about the Python-list mailing list