0%

Python_OrderDict

reference Adress:official Doc Learning Bolg

What?

An OrderedDict is a dictionary subclass that remembers the order in which its contents are added.
Compare with regular dict class, the OrderedDict remember the add sequentence and offer some functions to revise inner order;Intuitively,it more like a dict with list;

Feature?

1.Remember the order in which its contents are added

However Python3.7 dict has the same feature;So this feature is not matter any more;

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
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)
1
2
3
4
5
6
7
8
9
10
11
12
13
Regular dictionary:
a A
b B
c C
d D
e E

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

2.Offer functions to revise inner order

1.popitem(last=True)

The popitem() method for ordered dictionaries returns and removes a (key, value) pair. The pairs are returned in LIFO order if last is true or FIFO order if false.

2.move_to_end(key, last=True)

Move an existing key to either end of an ordered dictionary. The item is moved to the right end if last is true (the default) or to the beginning if last is false. Raises KeyError if the key does not exist:

1
2
3
4
5
6
7
8
9
d = collections.OrderedDict.fromkeys('abcde')
d.move_to_end("b")
"".join(d.keys())
# 'acdeb'

d.move_to_end("b" , last = False)
"".join(d.keys())
# 'bacde'

3.order-sensitive

A regular dict looks at its contents when testing for equality. An OrderedDict also considers the order the items were added.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
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)

# dict :
# True
# OrderedDict:
# False

Examples?

LRU function can be easility finished by OrderedDict.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
from collections import OrderedDict
class LRUCache(OrderedDict):

def __init__(self, capacity):

self.capacity = capacity

def get(self, key):

if key not in self:
return - 1

self.move_to_end(key)
return self[key]

def put(self, key, value):

if key in self:
self.move_to_end(key)
self[key] = value
if len(self) > self.capacity:
self.popitem(last = False)