collections模块中的OrderedDict类

字典能够将信息关联起来,但它们不记录键值对的顺序。OrederedDict实例的行为与字典相同,区别在于记录了添加的键值对的顺序。

In [1]: from collections import OrderedDict
In [2]: favorite_language = OrderedDict()
In [3]: favorite_language["zhangsan"] = "Enlish"
In [4]: favorite_language["lisi"] = "Chinese"
In [5]: favorite_language["wangwu"] = "French"
In [6]: favorite_language
Out[6]: 
OrderedDict([('zhangsan', 'Enlish'),
             ('lisi', 'Chinese'),
             ('wangwu', 'French')])
In [7]: for name, language in favorite_language.items():
    ...:     print(name +": " + language)    
    ...:     
zhangsan: Enlish
lisi: Chinese
wangwu: French
In [8]: type(favorite_language)
Out[8]: collections.OrderedDict

你可能感兴趣的:(collections模块中的OrderedDict类)