> ## Documentation Index
> Fetch the complete documentation index at: https://docs.syntblaze.com/llms.txt
> Use this file to discover all available pages before exploring further.

# Python dict

A Python `dict` (dictionary) is a built-in, mutable, and iterable mapping type that stores collections of key-value pairs. Backed by a highly optimized hash table, it provides O(1) average time complexity for lookups, insertions, and deletions. As of CPython 3.6 (and officially in the Python 3.7 language specification), dictionaries natively preserve insertion order.

## Key Characteristics

* **Hashable Keys:** Dictionary keys must be hashable. An object is hashable if it has a hash value that never changes during its lifetime (implementing a `__hash__()` method) and can be compared to other objects (implementing an `__eq__()` method). Immutable types like strings and integers are hashable. Tuples are hashable only if *all of their contained elements* are also hashable (e.g., `(1, 2)` is hashable, but `(1, [2, 3])` raises a `TypeError`). Mutable types like lists and other dictionaries are unhashable.
* **Arbitrary Values:** Dictionary values have no restrictions. They can be any Python object, including other dictionaries, functions, or custom class instances.
* **Reference Semantics:** Dictionaries store references to objects, not copies of the objects themselves.

## Syntax and Instantiation

Dictionaries can be created using literal syntax, the `dict()` constructor, or dictionary comprehensions.

```python theme={"dark"}

# 1. Literal syntax (most efficient)
user_data = {"id": 101, "username": "admin"}


# 2. Constructor using keyword arguments
user_data = dict(id=101, username="admin")


# 3. Constructor using an iterable of key-value pairs
user_data = dict([("id", 101), ("username", "admin")])


# 4. Dictionary comprehension
squares = {x: x**2 for x in range(5)}

# Result: {0: 0, 1: 1, 2: 4, 3: 9, 4: 16}
```

## Core Operations

### Accessing Values

Accessing a value via bracket notation raises a `KeyError` if the key is missing. The `.get()` method provides a safe alternative by returning `None` (or a specified default) if the key is not found.

```python theme={"dark"}
data = {"host": "localhost", "port": 8080}


# Direct access
port = data["port"]          # Returns 8080

# missing = data["timeout"]  # Raises KeyError


# Safe access
timeout = data.get("timeout", 30)  # Returns 30 (default fallback)
```

### Insertion, Updating, and Merging

Assigning a value to a key will insert the key if it does not exist, or overwrite the existing value if it does. The `.update()` method allows for bulk insertions or updates. Python 3.9 introduced the merge (`|`) and update (`|=`) operators, providing a standard, declarative way to combine dictionaries.

```python theme={"dark"}
data["protocol"] = "https"  # Inserts new key-value pair
data["port"] = 443          # Overwrites existing value


# Bulk update using another dictionary or iterable
data.update({"host": "127.0.0.1", "timeout": 60})


# Merge operator (|) creates a new dictionary (Python 3.9+)
defaults = {"timeout": 30, "retries": 3}
custom = {"retries": 5, "async": True}
merged = defaults | custom  # {"timeout": 30, "retries": 5, "async": True}


# Update operator (|=) modifies in-place (Python 3.9+)
defaults |= custom
```

### Deletion

Elements can be removed using the `del` statement, the `.pop()` method (which returns the removed value), or `.popitem()` (which removes and returns the last inserted key-value pair).

```python theme={"dark"}

# Removes key and returns its value; raises KeyError if missing
port = data.pop("port")


# Removes key without returning value
del data["host"]


# Removes and returns the last inserted (key, value) tuple (LIFO order)
last_item = data.popitem() 
```

## Dictionary Views

The methods `.keys()`, `.values()`, and `.items()` return dictionary view objects (`dict_keys`, `dict_values`, and `dict_items`). These are not static lists; they are dynamic views that reflect changes to the underlying dictionary in real-time.

```python theme={"dark"}
config = {"debug": True, "workers": 4}

keys_view = config.keys()
values_view = config.values()
items_view = config.items()


# Modifying the dictionary dynamically updates the views
config["timeout"] = 120

# keys_view now automatically includes "timeout"
```

The `dict_keys` view supports set operations (like union `|` and intersection `&`). The `dict_items` view also supports set operations, provided all values in the dictionary are hashable. The `dict_values` view does not support set operations because values are not guaranteed to be unique and do not behave like sets.

## Internal Architecture

Modern CPython implements dictionaries using a **compact dictionary** architecture. It maintains a dense array storing the actual key-value-hash entries in insertion order, and a separate sparse array of indices (the actual hash table) that points to the dense array.

When a key is looked up:

1. Python computes the hash of the key using `hash(key)`.
2. The hash is masked to find an index in the sparse array.
3. The sparse array provides the index of the actual entry in the dense array.
4. Python checks for hash collisions using open addressing and resolves them via a pseudo-random probing sequence.
5. Finally, it verifies equality using `__eq__()` to ensure the found key is the exact match, not just a hash collision.

<div
  style={{ 
display: "flex", 
justifyContent: "space-between", 
alignItems: "center", 
maxWidth: "754px", 
padding: "1rem 0",
marginBottom: "24px"
}}
>
  <span style={{ fontWeight: "bold", fontSize: "1.25rem", color: "var(--tw-prose-headings)", fontFamily: "Inter, ui-sans-serif, system-ui, sans-serif" }}>Tired of Poor Python Skills? Fix That With Deep Grasping!</span>

  <a
    href="https://syntblaze.com"
    target="_blank"
    style={{ 
  marginLeft: "24px",
  textDecoration: "none", 
  backgroundColor: "#007AFF",
  color: "#ffffff", 
  padding: "6px 16px", 
  borderRadius: "16px",
  fontSize: "0.9rem",
  fontWeight: "600",
  textAlign: "center",
  transition: "background-color 0.2s ease"
}}
  >
    Learn More
  </a>
</div>

<div style={{ display: "flex", gap: "12px", flexWrap: "wrap" }}>
  <img src="https://mintcdn.com/syntblazellc/-L0ums_2lctDSZ1l/images/skill-tracking.png?fit=max&auto=format&n=-L0ums_2lctDSZ1l&q=85&s=b9b0305c93bb501c9e767b5c76c88835" style={{ width: "30%", minWidth: 60 }} width="621" height="1344" data-path="images/skill-tracking.png" />

  <img src="https://mintcdn.com/syntblazellc/23tyuOzaWS88qFlc/images/nuggets.png?fit=max&auto=format&n=23tyuOzaWS88qFlc&q=85&s=c86c80197299762989e9b882419b2109" style={{ width: "30%", minWidth: 60 }} width="621" height="1344" data-path="images/nuggets.png" />

  <img src="https://mintcdn.com/syntblazellc/-L0ums_2lctDSZ1l/images/bite-sized-exercises.png?fit=max&auto=format&n=-L0ums_2lctDSZ1l&q=85&s=a65f9a38c37ff28ab73ed783c53c60e3" style={{ width: "30%", minWidth: 60 }} width="621" height="1344" data-path="images/bite-sized-exercises.png" />
</div>

<div style={{ display: "flex", gap: "12px", flexWrap: "wrap", marginTop: "12px" }}>
  <img src="https://mintcdn.com/syntblazellc/-L0ums_2lctDSZ1l/images/mastery-chain.png?fit=max&auto=format&n=-L0ums_2lctDSZ1l&q=85&s=748a1763454713e679260fbb95f154a2" style={{ width: "30%", minWidth: 60 }} width="621" height="1344" data-path="images/mastery-chain.png" />

  <img src="https://mintcdn.com/syntblazellc/-L0ums_2lctDSZ1l/images/element-previews.png?fit=max&auto=format&n=-L0ums_2lctDSZ1l&q=85&s=242f61448ff5dd6deaaab2dccc13b507" style={{ width: "30%", minWidth: 60 }} width="621" height="1344" data-path="images/element-previews.png" />

  <img src="https://mintcdn.com/syntblazellc/-L0ums_2lctDSZ1l/images/element-explanations.png?fit=max&auto=format&n=-L0ums_2lctDSZ1l&q=85&s=cf0fc1c31f9cd0fc26716781be05fbc9" style={{ width: "30%", minWidth: 60 }} width="621" height="1344" data-path="images/element-explanations.png" />
</div>
