"Python Cookbook" "Data Structure and algorithm" 7. Keep the dictionary in order

Source: Internet
Author: User

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

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.