Python Tutoring Online
 Home

Python Dictionary Time Complexity (Big O Guide)

Python dictionaries are known for their excellent performance. Most dictionary operations — lookup, insertion, and deletion — run in constant time, O(1), on average. This means the time required to perform these operations does not meaningfully increase as the dictionary grows from ten items to ten million.

This high efficiency comes from Python's use of a hash table internally, which lets it calculate the position of a value directly from its key instead of searching through every element. This guide breaks down the time complexity of every major dictionary operation, explains the difference between average and worst case, and compares dictionaries to other Python data structures so you know exactly when to reach for one.

Need Help Learning Python?

Understanding time complexity helps developers design efficient programs and algorithms.

Python dictionaries are widely used in data processing, web development, and machine learning because of their performance advantages.

Get Python Tutoring Help

A Quick Refresher on Big O Notation

Time complexity describes how the running time of an operation changes as the size of the input grows. It is expressed using Big O notation, which focuses on the growth trend rather than exact timings — it answers "what happens as n gets huge?" rather than "how many milliseconds does this take?"

Big O notation helps programmers estimate how efficient an algorithm or data structure is when handling large amounts of data, and it's the standard vocabulary used in technical interviews and performance discussions.

Full Complexity Table for Dictionary Operations

Operation Average Case Worst Case
Access element (d[key]) O(1) O(n)
Insert element (d[key] = value) O(1) amortized O(n)
Delete element (del d[key]) O(1) O(n)
Check if key exists (key in d) O(1) O(n)
.get(key) O(1) O(n)
.pop(key) O(1) O(n)
.keys() / .values() / .items() (view creation) O(1) O(1)
Iterate through dictionary O(n) O(n)
Copy (dict(d) or .copy()) O(n) O(n)
Merge (d1 | d2 or .update()) O(len of merged-in dict) O(n)
Equality check (d1 == d2) O(n) O(n)

In most practical situations, dictionary operations run in constant time. The O(n) worst cases listed above are theoretical bounds that occur only under pathological hash collision scenarios, which are rare in normal usage.

Why Insertion Is "Amortized" O(1)

You'll often see dictionary insertion described as amortized O(1) rather than simply O(1). This distinction matters. Most individual insertions are truly O(1), but occasionally, when the internal hash table becomes too full, Python must allocate a larger table and rehash every existing key into it — an O(n) operation.

Because this resize happens infrequently — roughly every time the dictionary doubles in size — its cost, when spread out ("amortized") across all the cheap O(1) insertions that happen between resizes, averages out to O(1) per insertion overall. This is the same amortized analysis used for Python lists when they grow beyond their allocated capacity.

Python
data = {}

# Each of these insertions is O(1) amortized,
# even though a small number of them internally
# trigger an O(n) resize behind the scenes
for i in range(100000):
    data[i] = i

print(len(data))

Output


100000

Example: Accessing a Dictionary Element — O(1)

Python
student = {
"name":"Alice",
"age":21,
"course":"Python"
}

print(student["name"])

Output


Alice

Accessing the value using the key takes constant time because Python directly calculates the location of the value using hashing, regardless of how many other keys are in the dictionary.

Example: Inserting a New Key — O(1) Amortized

Python
data = {}

data["a"] = 10
data["b"] = 20
data["c"] = 30

print(data)

Output


{'a': 10, 'b': 20, 'c': 30}

Adding a new key-value pair usually takes constant time because Python determines the correct position using the hash value, only occasionally paying the cost of a table resize.

Example: Deleting an Item — O(1)

Python
data = {
"a":10,
"b":20,
"c":30
}

del data["b"]

print(data)

Output


{'a': 10, 'c': 30}

Deleting a dictionary entry also runs in constant time on average, since Python locates the entry's slot directly via hashing rather than searching for it.

Checking if a Key Exists — O(1)

Python
data = {
"a":10,
"b":20,
"c":30
}

print("b" in data)

Output


True

Python quickly determines whether a key exists using hashing, which is why key in dict is the idiomatic and efficient way to test membership, rather than looping manually through .keys().

Dictionary Iteration Complexity — O(n)

Iterating through a dictionary requires visiting every element exactly once, so the time complexity grows linearly with the size of the dictionary. This is unavoidable — there's no way to visit every key without touching every key.

Python
data = {
"a":10,
"b":20,
"c":30
}

for key,value in data.items():
    print(key,value)

Output


a 10
b 20
c 30

Complexity of .keys(), .values(), and .items()

Calling .keys(), .values(), or .items() itself is O(1) — these methods don't copy any data, they return lightweight view objects that stay linked to the dictionary. The O(n) cost only happens when you actually iterate over the view, not when you create it.

Python
data = {"a": 1, "b": 2, "c": 3}

keys_view = data.keys()   # O(1) - just creates a view
print(list(keys_view))    # O(n) - this is what walks every key

Output


['a', 'b', 'c']

Because views stay linked to the original dictionary, they also reflect changes made after the view was created — another reason they're cheap to construct.

Worst Case Scenario: Hash Collisions

In rare situations, many keys may produce hash values that map to the same slot inside the hash table. This causes collisions and can, in the theoretical worst case, degrade operations from O(1) toward O(n), since Python may need to probe through several occupied slots before finding the right one.

However, Python dictionaries use well-tuned collision handling techniques (open addressing with pseudo-random probing) and a hash function designed to spread keys evenly, so worst-case performance is extremely uncommon in real programs. It typically only becomes a practical concern with adversarially crafted keys or a poorly written custom __hash__() method.

Dictionary Lookup vs List Search Complexity

Python
# List search - O(n)
numbers = [10,20,30,40,50]

print(40 in numbers)


# Dictionary lookup - O(1) average
data = {10:"a",20:"b",30:"c",40:"d"}

print(40 in data)

Output


True
True

Searching in a list requires scanning elements sequentially until a match is found — O(n) in the worst case. Dictionary lookup uses hashing to jump almost directly to the right slot — O(1) on average — making it dramatically faster for large collections.

Complexity Comparison: dict vs list vs set vs tuple

Choosing the right structure often comes down to which operation you'll perform most. Here's how the core structures compare for the operations that matter most.

Operation dict list set tuple
Access by index/key O(1) O(1) N/A O(1)
Search / membership (in) O(1) O(n) O(1) O(n)
Insert O(1) amortized O(1) amortized (end) / O(n) (middle) O(1) amortized Not supported (immutable)
Delete O(1) O(n) O(1) Not supported (immutable)
Ordered by insertion Yes (3.7+) Yes No Yes

This is why dictionaries and sets are the go-to choice whenever membership testing or key-based lookup is the dominant operation, while lists remain a good fit for ordered sequences accessed primarily by position.

Dictionary Size and Performance at Scale

Dictionary performance remains stable even when the number of elements becomes very large. Python automatically resizes the underlying hash table when the load factor crosses a threshold, allocating more space and rehashing existing entries.

This automatic resizing is exactly what keeps average-case lookup and insertion at O(1) even as a dictionary scales from a handful of entries to millions.

Practical Example with Large Data

Python
data = {}

for i in range(100000):
    data[i] = i

print(data[90000])

Output


90000

Even with a very large dictionary, Python retrieves values almost instantly, since lookup cost doesn't meaningfully scale with the number of stored items.

Space Complexity of Dictionaries

Time complexity isn't the whole story — space complexity matters too. A Python dictionary uses O(n) space, growing linearly with the number of stored key-value pairs. However, the constant factor is higher than a list's, since each entry also stores a cached hash and the table reserves extra empty slots to keep collisions low. This is the standard time-for-space trade-off: dictionaries spend more memory to buy faster average-case lookups.

Tips for Efficient Dictionary Usage

Frequently Asked Questions

Is dictionary lookup really always O(1)?

On average, yes, for well-distributed keys. The O(n) figure is strictly a worst-case bound driven by hash collisions, and in typical real-world code, you can reliably treat dictionary lookup as constant time.

Why is insertion called "amortized" O(1) but access is just "O(1)"?

Access never triggers a table resize, so its cost doesn't vary. Insertion occasionally triggers an O(n) resize when the table grows too full, so its true average cost is only O(1) when measured across many insertions — hence "amortized."

Is checking "key in dict" faster than "key in list"?

Yes, significantly, for anything beyond a tiny collection. Dictionary and set membership testing is O(1) on average via hashing, while list membership testing is O(n) because it must scan sequentially.

Does dictionary size affect lookup speed in practice?

Not meaningfully. Because lookup is O(1) on average, a dictionary with 10 items and one with 10 million items take roughly the same amount of time to access a single key, aside from cache-locality effects at extreme scales.

What's the time complexity of merging two dictionaries?

Using d1.update(d2) or the d1 | d2 merge operator (Python 3.9+) costs time proportional to the size of the dictionary being merged in — roughly O(len(d2)) — since each of its keys must be hashed and inserted individually.

Summary

Python dictionaries provide excellent performance because they use hash tables internally. Most operations — lookup, insertion, deletion, and membership testing — run in O(1) average-case time, with insertion specifically being amortized O(1) due to occasional table resizing.

Understanding dictionary time complexity — and how it compares to lists, sets, and tuples — helps developers choose the right data structure and write scalable, efficient Python programs.

Related Python Dictionary Tutorials




Stuck Learning Python?

Struggling with Python syntax, assignments or debugging errors? Learning alone can be frustrating.

Get 1-on-1 Python tutoring and learn faster with clear explanations, real examples and live help.

    Get Python Tutoring

PythonTutor.net

Home    Tutorial     Online Live Trainings    Contact Us           © 2026 All rights reserved by www.PythonTutor.net