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

Stefan Behnel stefan_ml at behnel.de
Mon Jul 23 07:43:14 EDT 2012


Henrik Faber, 23.07.2012 13:23:
> I have a question of which I'm unsure if the specification guarantees
> it. With an arbitrary dictionaty d, are d.keys() and d.values()
> guaraneed to be in the same order? I.e. what I mean is:
> 
> # For all dictionaries d:
> assert({ list(d.keys())[i]: list(d.values())[i] for i in range(len(d)) }
> == d)
> 
> I'm curious if it's allowed because in a special case it would make for
> a nice shortcut and clean code. I think however that the implementation
> may chose not to have them in the same order necessarily -- then I'd
> obviously avoid relying on it.

You should.

Stefan





More information about the Python-list mailing list