Skip to content

Commit 3557726

Browse files
committed
Adds OrderedDict
1 parent 53baeac commit 3557726

File tree

1 file changed

+37
-0
lines changed

1 file changed

+37
-0
lines changed

book/collections.md

+37
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@
66
А конкретно:
77

88
- `defaultdict`
9+
- `OrderedDict`
910
- `counter`
1011
- `deque`
1112
- `namedtuple`
@@ -78,6 +79,42 @@ print(json.dumps(some_dict))
7879
# Вывод: {"colours": {"favourite": "yellow"}}
7980
```
8081

82+
## `OrderedDict`
83+
84+
`OrderedDict` сохраняет элементы в порядке добавление в словарь. Иизменение
85+
значения ключа не изменяет его позиции. При этом удаление и повторное
86+
добавление перенесет ключ в конец словаря.
87+
88+
**Проблема:**
89+
90+
```python
91+
colours = {"Red": 198, "Green": 170, "Blue": 160}
92+
for key, value in colours.items():
93+
print(key, value)
94+
# Вывод:
95+
# Red 198
96+
# Blue 160
97+
# Green 170
98+
#
99+
# Элементы выводятся в произвольном порядке
100+
```
101+
102+
**Решение:**
103+
104+
```python
105+
from collections import OrderedDict
106+
107+
colours = OrderedDict([("Red", 198), ("Green": 170), ("Blue": 160)])
108+
for key, value in colours.items():
109+
print(key, value)
110+
# Вывод:
111+
# Red 198
112+
# Green 170
113+
# Blue 160
114+
#
115+
# Порядок элементов сохранен
116+
```
117+
81118
## `counter`
82119

83120
`Counter` позволяет подсчитывать частоту определенных элементов. К примеру,

0 commit comments

Comments
 (0)