OrderedDict ordered dictionary in the collections module of Python

Source: Internet
Author: User
The dictionary is unordered, but the OrderedDict class of collections provides us with an Ordered dictionary structure, which is a real Ordered + Dict, the following two examples are used to briefly understand the OrderedDict ordered dictionary in the collections module of Python: as the data structure name says, it records the order in which each key-value pair is added.

d = OrderedDict()d['a'] = 1d['b'] = 10d['c'] = 8for letter in d:  print letter

Output:

abc

If multiple parameters are input at the same time during initialization, their order is random and will not be stored in order of location.

>>> d = OrderedDict(a=1, b=2, c=3)OrderedDict([('a', 1), ('c', 3), ('b', 2)])

In addition to the same method as normal dict, OrderedDict also provides sequence-related operations: + popitem (): returns the last inserted key-value pair, if popitem (last = False) is returned, the first inserted key-value pair + reversed is returned.

Instance
In fact, OrderedDict can be viewed as a dictionary subclass:

import collectionsprint 'Regular dictionary:'d = {}d['a'] = 'A'd['b'] = 'B'd['c'] = 'C'for k, v in d.items():  print k, vprint '\nOrderDict:'d = collections.OrderedDict()d['a'] = 'A'd['b'] = 'B'd['c'] = 'C'for k, v in d.items():  print k, v

Conventional dict does not track the insertion sequence. iterative processing generates values based on the order in which keys are stored in the hash table. In OrderDict, it remembers the order of element insertion and uses this order when creating the iterator.

Regular dictionary:a Ac Cb BOrderDict:a Ab Bc C

Regular dict checks its content for equality, while OrderDict also considers the order in which elements are added.

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.