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

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

    Yes, what you observed is indeed a guaranteed property -- keys(), values() and items() return lists in congruent order if the dict is not altered. iterkeys() &c also iterate in the same order as the corresponding lists.

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

    Found this:

    If items(), keys(), values(), iteritems(), iterkeys(), and itervalues() are called with no intervening modifications to the dictionary, the lists will directly correspond.

    On 2.x documentation and 3.x documentation.

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

    Yes it is guaranteed in python 2.x:

    If keys, values and items views are iterated over with no intervening modifications to the dictionary, the order of items will directly correspond.

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

    Yes. Starting with CPython 3.6, dictionaries return items in the order you inserted them.

    Ignore the part that says this is an implementation detail. This behaviour is guaranteed in CPython 3.6 and is required for all other Python implementations starting with Python 3.7.

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

    I wasn't satisfied with these answers since I wanted to ensure the exported values had the same ordering even when using different dicts.

    Here you specify the key order upfront, the returned values will always have the same order even if the dict changes, or you use a different dict.

    keys = dict1.keys()
    ordered_keys1 = [dict1[cur_key] for cur_key in keys]
    ordered_keys2 = [dict2[cur_key] for cur_key in keys]
    
    0 讨论(0)
  • 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
    
    0 讨论(0)
提交回复
热议问题