Problem: When creating a dictionary, you can also control the order of elements in the dictionary while iterating or serializing it;
Solution: You can use the Ordereddict class in the Collections module to control the order of elements in the dictionary. When the dictionary is iterated, he is strictly in the order in which the elements are initially added. For example:
from collections import ORDEREDDICTD =ordereddict () d[ foo "]=1 d[ " bar "]=2d[ spam ] =3d[ " "]=4for key in D: print (Key,d[key])
Python 3.4.0 (v3.4.0:04f714765c13, Mar, 19:24:06) [MSC v.1600 32 bit (Intel)] O n win32type copyright ", " credits " or " for more information. >>> ================================ RESTART ================================>>> foo 1bar 2spam 3grok 4>>>
Ordereddict is especially useful when you want to build a mapping structure so that you can serialize it later or encode it into another format.
For example, if you want to precisely control the order of the fields in JSON encoding, you can just build the 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} >>>
Add: Ordereddict internally maintains a doubly linked list, which arranges the position of the keys according to the order in which they are added. The first newly added element is placed at the end of the list, and subsequent re-assignment of the existing key does not change the order of the keys.
Note: The size of the ordereddict is twice times that of the normal dictionary, which is caused by the list of additional links created. So when building structures that involve large amounts of data, weigh the benefits and memory consumed.
"Python Cookbook" "Data Structure and algorithm" 7. Keep the dictionary in order