Article directory
foreword
Record new knowledge encountered in work, as an essay
1. Ordered dictionary
Because the dictionary itself is a hash table, it is unordered. And sometimes specific scenarios require ordered dictionaries.
An ordered dictionary is similar to a normal dictionary, except that it can record the order in which elements are inserted into it, while a normal dictionary will iterate in any order.
2. Use steps
1. Import library
import collections
2. Instantiate an ordered dictionary object
dic = collections.OrderedDict()
3. Dynamically add and output in the order of addition
dic = collections.OrderedDict()
dic['a'] = 'A'
dic['b'] = 'B'
dic['c'] = 'C'
dic['d'] = 'D'
print(dic)
#输出内容:OrderedDict([('a', 'A'), ('b', 'B'), ('c', 'C'), ('d', 'D')])
4. Precautions
Ordered dictionaries are output in insertion order
import collections
dic = {
'a':'A','b':'B','c':'C','d':'D'}
dic = collections.OrderedDict()
print(d2)
输出结果为空
Summarize
Using an ordered dictionary needs to be instantiated in advance, and then inserted in the desired order. OrderedDict can implement a FIFO (first in, first out) dict. When the capacity exceeds the limit, delete the earliest added Key first.