Python cookbook (data structures and algorithms) keeps the dictionary orderly.
This example describes how to keep the dictionary in order by using Python. We will share this with you for your reference. The details are as follows:
Problem:When creating a dictionary and performing iteration or serialization operations on the dictionary, you can also control the order of its elements;
Solution:You can use the OrderedDict class in the collections module to control the order of the elements in the dictionary. When the dictionary is iterated, it will strictly follow the sequence of initial addition of elements. For example:
from collections import OrderedDictd=OrderedDict()d['foo']=1d['bar']=2d['spam']=3d['grok']=4for key in d: print(key,d[key])
Python 3.4.0 (v3.4.0:04f714765c13, Mar 16 2014, 19:24:06) [MSC v.1600 32 bit (Intel)] on win32Type "copyright", "credits" or "license()" for more information.>>> ================================ RESTART ================================>>> foo 1bar 2spam 3grok 4>>>
OrderedDict is particularly useful when you want to build a ing structure so that it can be serialized or encoded into another format later.
For example, if you want to precisely control the order of each field during JSON encoding, you only need to build data in OrderedDict first.
>>> import json>>> dOrderedDict([('foo', 1), ('bar', 2), ('spam', 3), ('grok', 4)])>>> json.dumps(d)'{"foo": 1, "bar": 2, "spam": 3, "grok": 4}'>>>
Supplement:OrderedDict maintains a two-way linked list, which sorts the key locations according to the order in which the elements are added. The first newly added element is placed at the end of the linked list. reassigning values to existing keys does not change the key order.
Note:OrderedDict is twice the size of a common dictionary, which is caused by its additional linked list. Therefore, when constructing a structure involving a large amount of data, we must weigh the benefits and memory consumption.
(The code is from Python Cookbook.)