> For the complete documentation index, see [llms.txt](https://kaze.gitbook.io/qa-theory/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://kaze.gitbook.io/qa-theory/osnovy-programmirovaniya-na-python/osobennosti-slovarei.md).

# Особенности словарей

### **1. Основные особенности словарей**

1. **Ключи уникальны**
   * В словаре **не может быть одинаковых ключей**. Если добавить ключ, который уже существует, его значение обновится:

```python
d = {"a": 1, "b": 2}
d["a"] = 10
print(d)  # {'a': 10, 'b': 2}
```

2. **Ключи неизменяемы**
   * Ключи могут быть **числа, строки, кортежи**, но не **списки или словари**:

```python
d = {(1, 2): "tuple"}  # допустимо
# d[[1, 2]] = "list"   # TypeError
```

3. **Неупорядоченность до Python 3.6**
   * До Python 3.6 словари **не гарантировали порядок элементов**.
   * Начиная с Python 3.7, словари **сохраняют порядок добавления элементов**.
4. **Быстрый доступ по ключу**
   * Доступ к элементу по ключу происходит **за O(1)**, что быстрее, чем поиск в списке.
5. **Значения могут быть любыми**
   * В словарь можно хранить **числа, строки, списки, кортежи, другие словари, объекты**:

```python
d = {"num": 10, "list": [1,2], "dict": {"a": 1}}
```

6. **Методы для безопасной работы**
   * `get()` — безопасное получение значения
   * `setdefault()` — добавляет ключ только если его нет
   * `pop()` и `popitem()` — удаление с возвратом значения

***

### **2. Примеры использования в автотестах**

#### **2.1 Обработка JSON/API**

```python
response = {"status": "ok", "data": {"id": 1, "name": "Alice"}}
assert response.get("status") == "ok"
```

#### **2.2 Хранение сложных данных**

```python
users = {
    "user1": {"password": "123", "active": True},
    "user2": {"password": "456", "active": False}
}
assert users["user1"]["active"] is True
```

#### **2.3 Фильтрация данных**

```python
users = [{"name": "Alice", "active": True}, {"name": "Bob", "active": False}]
active_users = [u for u in users if u.get("active")]
print(active_users)  # [{'name': 'Alice', 'active': True}]
```


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://kaze.gitbook.io/qa-theory/osnovy-programmirovaniya-na-python/osobennosti-slovarei.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
