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

OrderedDict ordered dictionary in Python's collections module

WBOY
WBOYOriginal
2016-07-22 08:56:231377browse

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

Output:

a
b
c

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)])

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

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

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

Statement:
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