this article tells the way that Python keeps the dictionary in order. Share to you for your reference, as follows:

: to create a dictionary, and iterative or serialization operation on the dictionary, can also control the order of the elements;

solutions: can use the collections module in the OrderedDict class to control the order of the elements in the dictionary. When the dictionary is iterated, he will follow the order of the initial addition of the element. For example:

 from collections import OrderedDict d=OrderedDict (d['foo']=1) d['bar']=2 d['spam']=3 d['grok']=4 for key in d: print (key, d[key]) 
 Python 3.4.0 (v3.4.0:04f714765c13, Mar 162014, 19:24:06 32) [MSC v.1600 bit (Intel)] on Win32 Type "copyright", "credits" or "license (for more information.)" > > > RESTART > > Ran Ran; > foo 1 bar 2 spam 3 grok 4 > > & gt; 

; when you want to build a mapping structure for later the serialization or encoding into another format, it is especially useful for OrderedDict.

, for example: if you want to accurately control the order of each field in the JSON encoding, it is possible to build the data in the OrderedDict first.

 > > > import JSON > > > D OrderedDict ("('foo', 1), ('bar', 2), ('spam', 3), ('grok', 4)]) > > > json.dumps (d)'{: 1" foo "," bar "2," spam ": 3, grok: 4}'> > > 

added: OrderedDict internal maintenance of a two-way linked list, it will be based on the order of the key elements to the position. The first newly added element is placed at the end of the list, and then reassigning the existing keys does not change the order of the keys.

note: the size of the OrderedDict is 2 times the size of the ordinary dictionary, which is the result of the additional chain table that it creates. So when you build a structure that involves a lot of data, you have to weigh the benefits and the memory that it brings.

("Python Cookbook")

more Python on the relevant content of interested readers can see the special station: "Python data structure and algorithm tutorial " and "Python ", summarizes the skills in the use of function "Python " string manipulation skills summary, "Python entry and advanced tutorial classic " and "Python

operation skills summary" hope for all the Python programming help.

you might be interested in this article:

This concludes the body part

This paper fixed link: | Script Home | +Copy Link

Article reprint please specify:Python Cookbook (data structure and algorithm) way to keep the dictionary in order | Script Home

You may also be interested in these articles!