Python TypeError

Python TypeError: unhashable type 'dict' β€” Causes & Fix

Python TypeError: unhashable type 'dict' β€” json.dumps fix

What Does This Error Mean?

Python raises TypeError: unhashable type: 'dict' when you try to use a dictionary as a key in another dictionary or as a set element. Dictionaries are mutable β€” they have no stable hash value, so Python refuses to use them where a hashable object is expected.

Common Causes (With Code)

1. Using a dict as a dictionary key

❌ Causes the error

cache = {}
params = {"page": 1, "limit": 10}
cache[params] = "result"
# TypeError: unhashable type: 'dict'

2. Adding a dict to a set

❌ Causes the error

seen = set()
record = {"id": 42, "name": "Alice"}
seen.add(record)
# TypeError: unhashable type: 'dict'

3. Nested dict inside set comprehension

❌ Causes the error

rows = [{"id": 1}, {"id": 2}, {"id": 1}]
unique = {row for row in rows}
# TypeError: unhashable type: 'dict'

How to Fix It

Fix 1 β€” Serialize the dict to a string key

βœ… Correct

import json

cache = {}
params = {"page": 1, "limit": 10}
key = json.dumps(params, sort_keys=True)   # '{"limit": 10, "page": 1}'
cache[key] = "result"
print(cache)  # {'{"limit": 10, "page": 1}': 'result'}

Fix 2 β€” Convert to a tuple of items (sorted for consistency)

βœ… Correct

params = {"page": 1, "limit": 10}
key = tuple(sorted(params.items()))   # (('limit', 10), ('page', 1))
cache = {key: "result"}
print(cache)

Fix 3 β€” Track uniqueness by a hashable field instead of the whole dict

βœ… Correct

rows = [{"id": 1}, {"id": 2}, {"id": 1}]
seen_ids = set()
unique = []
for row in rows:
    if row["id"] not in seen_ids:
        seen_ids.add(row["id"])
        unique.append(row)
print(unique)  # [{'id': 1}, {'id': 2}]

Fix 4 β€” Use frozenset for flat key–value dicts

βœ… Correct

params = {"page": 1, "limit": 10}
key = frozenset(params.items())
cache = {key: "result"}
print(cache)

Frequently Asked Questions

Can I use a dict as a dict value?

Yes β€” dicts are perfectly valid as dictionary values and list elements. The restriction only applies to keys (in dicts and sets) which require a stable hash.

config = {"db": {"host": "localhost", "port": 5432}}   # βœ… Fine

What's the best approach for caching API calls keyed by params?

Use json.dumps(params, sort_keys=True) for readability, or tuple(sorted(params.items())) for performance. Both produce a stable, hashable key even if the dict insertion order varies.