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

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

提交回复
热议问题