参考链接: OrderedDict 对象
实验演示:
Microsoft Windows [版本 10.0.18363.1198]
(c) 2019 Microsoft Corporation。保留所有权利。
C:\Users\chenxuqi>python
Python 3.7.4 (tags/v3.7.4:e09359112e, Jul 8 2019, 20:34:20) [MSC v.1916 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> from collections import OrderedDict
>>>
>>> # regular unsorted dictionary
... d = {'banana7': 3, 'apple6': 4, 'pear5': 1, 'orange_8': 2}
>>> d
{'banana7': 3, 'apple6': 4, 'pear5': 1, 'orange_8': 2}
>>>
>>>
>>> # dictionary sorted by key
... sorted(d.items(), key=lambda t: t[0])
[('apple6', 4), ('banana7', 3), ('orange_8', 2), ('pear5', 1)]
>>> type(sorted(d.items(), key=lambda t: t[0]))
<class 'list'>
>>>
>>>
>>> # dictionary sorted by value
... sorted(d.items(), key=lambda t: t[1])
[('pear5', 1), ('orange_8', 2), ('banana7', 3), ('apple6', 4)]
>>>
>>>
>>> # dictionary sorted by length of the key string
... sorted(d.items(), key=lambda t: len(t[0]))
[('pear5', 1), ('apple6', 4), ('banana7', 3), ('orange_8', 2)]
>>>
>>>
>>>
>>>
>>>
>>>
>>>
>>>
>>> # regular unsorted dictionary
... d = {'banana': 3, 'apple': 4, 'pear': 1, 'orange': 2}
>>>
>>> # dictionary sorted by key
... OrderedDict(sorted(d.items(), key=lambda t: t[0]))
OrderedDict([('apple', 4), ('banana', 3), ('orange', 2), ('pear', 1)])
>>>
>>>
>>> # dictionary sorted by value
... OrderedDict(sorted(d.items(), key=lambda t: t[1]))
OrderedDict([('pear', 1), ('orange', 2), ('banana', 3), ('apple', 4)])
>>>
>>>
>>> # dictionary sorted by length of the key string
... OrderedDict(sorted(d.items(), key=lambda t: len(t[0])))
OrderedDict([('pear', 1), ('apple', 4), ('banana', 3), ('orange', 2)])
>>>
>>>
>>> myOD = OrderedDict(sorted(d.items(), key=lambda t: t[0]))
>>> myOD['apple']
4
>>> myOD['pear']
1
>>> len(myOD)
4
>>> type(myOD)
<class 'collections.OrderedDict'>
>>>
>>>
>>>
实验代码展示:
Python 3.7.4 (tags/v3.7.4:e09359112e, Jul 8 2019, 20:34:20) [MSC v.1916 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license()" for more information.
>>> from collections import OrderedDict
>>> ls = [('0','慧慧'),('1','大海'),('a','慧海'),('b','海海')]
>>> ls
[('0', '慧慧'), ('1', '大海'), ('a', '慧海'), ('b', '海海')]
>>> od = OrderedDict(ls)
>>> od
OrderedDict([('0', '慧慧'), ('1', '大海'), ('a', '慧海'), ('b', '海海')])
>>> od[0]
Traceback (most recent call last):
File "<pyshell#5>", line 1, in <module>
od[0]
KeyError: 0
>>> od['0']
'慧慧'
>>> od['1']
'大海'
>>> od['a']
'慧海'
>>> od['b']
'海海'
>>>
>>>
>>> type(od)
<class 'collections.OrderedDict'>
>>>
>>>
>>>