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

后端 未结 8 1581
难免孤独
难免孤独 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:46

    For what it's worth, some heavy used production code I have written is based on this assumption and I never had a problem with it. I know that doesn't make it true though :-)

    If you don't want to take the risk I would use iteritems() if you can.

    for key, value in myDictionary.iteritems():
        print key, value
    

提交回复
热议问题