咱們應該會在實際使用中發現python的字典是無序的,譬如說這樣python
>>> a = {'key1':'a','key2':'b','key3':'c','key4':'d','key5':'e'} >>> a {'key3': 'c', 'key2': 'b', 'key1': 'a', 'key5': 'e', 'key4': 'd'} >>>
那如何生成一個有序的字典呢,可使用collections模塊中的OrderdDict類,能夠這樣數據結構
>>> from collections import OrderedDict >>> a = OrderedDict() >>> a['key1'] = 'a' >>> a['key2'] = 'b' >>> a['key3'] = 'c' >>> a['key4'] = 'd' >>> a['key5'] = 'e' >>> a OrderedDict([('key1', 'a'), ('key2', 'b'), ('key3', 'c'), ('key4', 'd'), ('key5', 'e')])
由於OrderdDict比普通的字典要大,若是要設計大量的OrderdDict的數據結構時,會額外消耗系統資源,因此使用前須要斟酌。ide