Home > Backend Development > Python Tutorial > OrderedDict ordered dictionary in Python's collections module

OrderedDict ordered dictionary in Python's collections module

WBOY
Release: 2016-07-22 08:56:23
Original
1436 people have browsed it

As the name of this data structure says, it records the order in which each key-value pair is added.

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

Copy after login

Output:

a
b
c
Copy after login

If multiple parameters are passed in at the same time during initialization, their order will be random and will not be stored in positional order.

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

In addition to the same methods as normal dict, OrderedDict also provides order-related operations: + popitem(): Returns the last inserted key-value pair, if popitem(last=False) will return the first one Inserted key-value pair + reversed: Returns a reversed OrderedDict

Example
In fact, OrderedDict can be regarded as a dictionary subclass:

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

Regular dict does not keep track of insertion order, iterative processing generates values ​​based on the order in which the keys are stored in the hash table. The opposite is true in OrderDict, which remembers the order in which elements were inserted and uses this order when creating the iterator.

Regular dictionary:
a A
c C
b B
OrderDict:
a A
b B
c C
Copy after login

Regular dict will look at its contents when checking equality, and OrderDict will also consider the order in which elements are added.

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