字典能够将信息关联起来,但它们不记录添加键—值对的顺序。
要创建字典并记录其中的键—值对的添加顺序,可使用模块collections中的OrderedDict类。
OrderedDict实例的行为几乎与字典相同,区别只在于记录了键—值对的添加顺序。
from collections import OrderedDict
# 调用OrderedDict()来创建一个空的有序字典
favorite_languages = OrderedDict()
favorite_languages['jen'] = 'python'
favorite_languages['sarah'] = 'c'
favorite_languages['edward'] = 'ruby'
favorite_languages['phil'] = 'python'
for name, language in favorite_languages.items():
print(name.title() + "'s favorite language is " + language.title() + ".")