Python创建有序词典
示例
您可以创建有序字典,当对字典中的键进行迭代时,该字典将遵循确定的顺序。
OrderedDict从collections模块使用。迭代时,这将始终以原始插入顺序返回字典元素。
from collections import OrderedDict d = OrderedDict() d['first'] = 1 d['second'] = 2 d['third'] = 3 d['last'] = 4 # Outputs "first 1", "second 2", "third 3", "last 4" for key in d: print(key, d[key])