OrderedDict and pythonordereddict

Source: Internet
Author: User

OrderedDict and pythonordereddict

Ordered dictionary-OrderedDict Introduction

Example

An ordered dictionary is similar to a common dictionary, but it records the order in which elements are inserted, while a general dictionary iterates in any order. See the following example:

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

The running result is as follows:

-> python test7.pyRegular dictionary:a Ac Cb Be Ed DOrderedDict:a Ab Bc Cd De E

We can see that the dictionary is not traversed in the insert order.

Equality

To determine whether two ordered fields are equal (=), consider whether the order of element insertion is equal.

import collectionsprint 'dict    :',d1 = {}d1['a'] = 'A'd1['b'] = 'B'd1['c'] = 'C'd1['d'] = 'D'd1['e'] = 'E'd2 = {}d2['e'] = 'E'd2['d'] = 'D'd2['c'] = 'C'd2['b'] = 'B'd2['a'] = 'A'print d1 == d2print 'OrderedDict:',d1 = collections.OrderedDict()d1['a'] = 'A'd1['b'] = 'B'd1['c'] = 'C'd1['d'] = 'D'd1['e'] = 'E'd2 = collections.OrderedDict()d2['e'] = 'E'd2['d'] = 'D'd2['c'] = 'C'd2['b'] = 'B'd2['a'] = 'A'print d1 == d2

The running result is as follows:

-> python test7.pydict    : TrueOrderedDict: False

When determining whether an ordered dictionary is equal to other common dictionaries, you only need to determine whether the content is equal.

Note:

Although the OrderedDict constructor or the update () method accepts the keyword parameter, the order of the keyword parameter is lost because the python function call uses an unordered dictionary to pass the parameter, therefore, the order of the created ordered dictionary cannot be guaranteed.

References

Https://docs.python.org/2/library/collections.html#collections.OrderedDict
Https://pymotw.com/2/collections/ordereddict.html

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.