Key-value consistency in python dictionaries
--
Music by Eric Matyas
https://www.soundimage.org
Track title: RPG Blues Looping
--
Chapters
00:00 Question
00:25 Accepted answer (Score 7)
00:55 Answer 2 (Score 3)
01:24 Answer 3 (Score 2)
02:19 Thank you
--
Full question
https://stackoverflow.com/questions/8363...
Accepted answer links:
http://docs.python.org/library/stdtypes....
Answer 2 links:
http://docs.python.org/library/stdtypes....
Answer 3 links:
[documentation]: http://docs.python.org/library/stdtypes....
--
Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...
--
Tags
#python
#avk47
ACCEPTED ANSWER
Score 7
Yes it's always true. Guaranteed by Python iff there are no intervening modifications to the ditionary.
Relevant spec: http://docs.python.org/library/stdtypes.html#dict.items
This is better generally, both because it protects against the dict going out of sync and uses negligible extra memory:
dict((k,v) for k,v in d.iteritems())
ANSWER 2
Score 3
Yes, this is a guaranteed behavior :-)
The keys and values are listed in the same order as returned by d.items: http://docs.python.org/library/stdtypes.html#dict.items
Note, in multi-threaded environments it is best to extract d.items() all at once rather than risk a mutation between successive calls to d.keys() and d.values().
ANSWER 3
Score 2
If you're asking whether the keys and values are returned in the same order, the answer is Yes. The documentation says:
If
items(),keys(),values(),iteritems(),iterkeys(), anditervalues()are called with no intervening modifications to the dictionary, the lists will directly correspond.
If you're asking whether dict( zip( d.keys(), d.values() ) ) == d will always evaluate to True under all circumstances, the answer is No. You can have multiple threads, with one changing d while the other one is executing d.keys(), d.values(), or dict(...). This will create intervening modifications, invalidating the conditions quoted above.