Python dictionary: are keys() and values() always the same order?

后端 未结 8 1584
难免孤独
难免孤独 2020-11-22 12:18

It looks like the lists returned by keys() and values() methods of a dictionary are always a 1-to-1 mapping (assuming the dictionary is not altered

相关标签:
8条回答
  • 2020-11-22 12:47

    According to http://docs.python.org/dev/py3k/library/stdtypes.html#dictionary-view-objects , the keys(), values() and items() methods of a dict will return corresponding iterators whose orders correspond. However, I am unable to find a reference to the official documentation for python 2.x for the same thing.

    So as far as I can tell, the answer is yes, but only in python 3.0+

    0 讨论(0)
  • 2020-11-22 12:50

    Good references to the docs. Here's how you can guarantee the order regardless of the documentation / implementation:

    k, v = zip(*d.iteritems())
    
    0 讨论(0)
提交回复
热议问题