Python保证遍历字典所有元素,但不保证遍历的顺序,假如我们期望按预先的顺序进行遍历的话,可以通过两个List分别存储Key和Value,然后通过zip合并为Dictionary,再遍历:
# 通过zip方法合并两个List为Dictionary
# 遍历会按原先的顺序
keys = ["b", "a", "c", "e", "d"] values = ["2", "1", "3", "5", "4"] for key,value in zip(keys, values): print(key,value) # -- OUTPUT -- # b 2 # a 1 # c 3 # e 5 # d 4