OrderedDict is like dict but have some extra capabilities relating to ordering operation.
OrderedDict is designed to be good at reordering operations. Space efficiency, iteration speed, and the performance of update operations were secondary.
from collections import OrderedDict
d = OrderedDict()
d['apple'] = 1
d['banana'] = 2
d['cherry'] = 3
for k, v in d.items():
print(k, v)
# apple 1
# banana 2
# cherry 3
Methods
popitem(last=True)
This method returns and removes a (key, value) pair.
The pairs are returned in LIFO order if last is true or FIFO order if false.
d = OrderedDict()
d['apple'] = 1
d['banana'] = 2
d['cherry'] = 3
print(d)
# OrderedDict([('apple', 1), ('banana', 2), ('cherry', 3)])
print(d.popitem())
# ('cherry', 3)
print(d.popitem(False))
#('apple', 1)
move_to_end(key, last=True)
Move an existing key to either end of an OrderedDict.
Raises KeyError if the key does not exist.
d = OrderedDict()
d['apple'] = 1
d['banana'] = 2
d['cherry'] = 3
print(d)
# OrderedDict([('apple', 1), ('banana', 2), ('cherry', 3)])
d.move_to_end('apple')
print(d)
# OrderedDict([('banana', 2), ('cherry', 3), ('apple', 1)])
d.move_to_end('cherry', False)
print(d)
# OrderedDict([('cherry', 3), ('banana', 2), ('apple', 1)])
Conclusion
dict is an unordered data structure in Python.
If you need an ordered dictionary, you can try OrderedDict.
'Python' 카테고리의 다른 글
[Python] namedtuple in collections (0) | 2021.05.02 |
---|---|
[Python] Counter in collections (0) | 2021.05.01 |
[Python] defaultdict in collections (0) | 2021.05.01 |
[Python] deque in collections (0) | 2021.04.30 |
[Python] Underscore Usage (0) | 2021.04.26 |
댓글