Key-value consistency in python dictionaries
Rise to the top 3% as a developer or hire one of them at Toptal: https://topt.al/25cXVn
--------------------------------------------------
Music by Eric Matyas
https://www.soundimage.org
Track title: Puzzle Game 5
--
Chapters
00:00 Key-Value Consistency In Python Dictionaries
00:20 Accepted Answer Score 7
00:44 Answer 2 Score 3
01:09 Answer 3 Score 2
01:50 Thank you
--
Full question
https://stackoverflow.com/questions/8363...
--
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.