0
0
PythonHow-ToBeginner · 3 min read

How Python Dictionary Works Internally: Explained Simply

A Python dictionary stores data as key-value pairs using a hash table internally. Each key is hashed to find an index where its value is stored, allowing very fast access. When two keys hash to the same index, Python handles this collision by probing for the next free slot.
📐

Syntax

A Python dictionary is created using curly braces {} with key-value pairs separated by colons. Keys must be immutable types like strings or numbers, and values can be any type.

  • Key: The unique identifier used to access the value.
  • Value: The data stored and retrieved by the key.
python
my_dict = {"apple": 3, "banana": 5, "orange": 2}
💻

Example

This example shows how to create a dictionary, add items, and access values by keys. It demonstrates the fast lookup feature of dictionaries.

python
my_dict = {"apple": 3, "banana": 5}
my_dict["orange"] = 2
print(my_dict["banana"])
print(my_dict)
Output
5 {'apple': 3, 'banana': 5, 'orange': 2}
⚠️

Common Pitfalls

Common mistakes include using mutable types like lists as keys, which causes errors because keys must be hashable. Another pitfall is assuming dictionary order before Python 3.7, where order was not guaranteed.

Also, modifying a dictionary while iterating over it can cause runtime errors.

python
try:
    bad_dict = {[1, 2]: "value"}  # This will raise a TypeError
except TypeError as e:
    print(f"Error: {e}")

# Correct way:
good_dict = {(1, 2): "value"}  # Using a tuple which is immutable
print(good_dict)
Output
Error: unhashable type: 'list' {(1, 2): 'value'}
📊

Quick Reference

  • Dictionaries use a hash table internally for fast key lookup.
  • Keys must be immutable and hashable.
  • Collisions are handled by probing for empty slots.
  • Insertion, deletion, and lookup are on average O(1) time complexity.

Key Takeaways

Python dictionaries use hash tables to store key-value pairs for fast access.
Keys must be immutable and hashable to be used in dictionaries.
Collisions in hash tables are resolved by probing for the next available slot.
Dictionary operations like lookup, insert, and delete are very fast on average.
Avoid using mutable types as keys and modifying dictionaries during iteration.