Skip to content

Commit

Permalink
Adds OrderedDict
Browse files Browse the repository at this point in the history
  • Loading branch information
lancelote committed Feb 15, 2017
1 parent 53baeac commit 3557726
Showing 1 changed file with 37 additions and 0 deletions.
37 changes: 37 additions & 0 deletions book/collections.md
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
А конкретно:

- `defaultdict`
- `OrderedDict`
- `counter`
- `deque`
- `namedtuple`
Expand Down Expand Up @@ -78,6 +79,42 @@ print(json.dumps(some_dict))
# Вывод: {"colours": {"favourite": "yellow"}}
```

## `OrderedDict`

`OrderedDict` сохраняет элементы в порядке добавление в словарь. Иизменение
значения ключа не изменяет его позиции. При этом удаление и повторное
добавление перенесет ключ в конец словаря.

**Проблема:**

```python
colours = {"Red": 198, "Green": 170, "Blue": 160}
for key, value in colours.items():
print(key, value)
# Вывод:
# Red 198
# Blue 160
# Green 170
#
# Элементы выводятся в произвольном порядке
```

**Решение:**

```python
from collections import OrderedDict

colours = OrderedDict([("Red", 198), ("Green": 170), ("Blue": 160)])
for key, value in colours.items():
print(key, value)
# Вывод:
# Red 198
# Green 170
# Blue 160
#
# Порядок элементов сохранен
```

## `counter`

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

0 comments on commit 3557726

Please sign in to comment.