Question:
Are the lists generated by the keys() and values() methods of a Python dictionary always preserved in a one-to-one correspondence?
Example:
Assumption:
If a dictionary remains unmodified between calling keys() and values(), can we assume that the above loop will consistently print True for all elements?
Answer:
According to the official Python documentation for 2.x and 3.x:
If items(), keys(), values(),
iteritems(), iterkeys(), and
itervalues() are called with no
intervening modifications to the
dictionary, the lists will directly
correspond.
Therefore, our assumption is correct. As long as the dictionary is not altered between calling keys() and values(), the lists returned by these methods will always maintain a one-to-one mapping.
The above is the detailed content of Do Python dictionary keys() and values() methods return lists with matching order?. For more information, please follow other related articles on the PHP Chinese website!