Skip to main content

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.

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.

# 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.
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.
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).

# 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.
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.
Master Python with Deep Grasping Methodology!Learn More