Home > Backend Development > Python Tutorial > Introduction to python module: Ordered Dict (OrderedDict)

Introduction to python module: Ordered Dict (OrderedDict)

WBOY
Release: 2016-12-05 13:27:17
Original
1262 people have browsed it

Ordered Dictionary-Introduction to OrderedDict

Example

An ordered dictionary is similar to a normal dictionary, except that it can record the order in which elements are inserted into it, while a normal dictionary will iterate in any order. See example below:

import collections

print '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, v

print '\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

Copy after login

The running results are as follows:

-> python test7.py
Regular dictionary:
a A
c C
b B
e E
d D

OrderedDict:
a A
b B
c C
d D
e E

Copy after login

You can see that usually dictionaries are not traversed in insertion order.

Equality

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

import collections

print '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 == d2

print '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

Copy after login

The running results are as follows:

-> python test7.py
dict    : True
OrderedDict: False
Copy after login

When judging whether an ordered dictionary is equal to other ordinary dictionaries, you only need to judge whether the contents are equal.

Attention

Although the constructor or update() method of OrderedDict accepts keyword parameters, because python function calls use unordered dictionaries to pass parameters, the order of keyword parameters will be lost, so the created ordered dictionary cannot be guaranteed. its order.

References

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

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template