Understanding and Fixing TypeError: dict is not a sequence in Python
When writing Python code, encountering errors is part of the learning curve. Which means one message that often puzzles beginners and even intermediate developers is TypeError: dict is not a sequence. This error signals a fundamental misunderstanding of Python's data type hierarchy—specifically, the distinction between sequences and mappings. In this article, we’ll break down exactly what this error means, why it happens, and how to resolve it efficiently in your projects The details matter here. That alone is useful..
What the Error Actually Means
In Python, data types are categorized into several groups: sequences, mappings, sets, and more. Sequences—such as lists, tuples, and strings—are ordered collections that support indexing, slicing, and operations like len() and iteration via integer positions. So naturally, Mappings, on the other hand, are represented by dictionaries (dict). A dictionary is a mapping object that pairs keys with values; it does not support the sequence protocol.
When you attempt to treat a dictionary as if it were a list or tuple—such as trying to access it by a numeric index, slice it, or use sequence-specific functions—Python raises TypeError: dict is not a sequence. The error is Python’s way of protecting you
from silently producing incorrect results by enforcing strict type boundaries.
Common Scenarios That Trigger the Error
1. Passing a Dictionary Where a Sequence Is Expected
Many built-in functions and library APIs expect sequences. That said, choice(), statistics. As an example, random.mean(), or database parameter placeholders often require a list or tuple And that's really what it comes down to..
import random
config = {"host": "localhost", "port": 5432}
random.choice(config) # TypeError: dict is not a sequence
Here, random.choice() expects a sequence to pick an index from. A dictionary has no integer indices, so Python refuses the operation.
2. Incorrect String Formatting with % Operator
The % formatting operator behaves differently depending on the right-hand operand. When the left side contains multiple % specifiers, the right side must be a tuple (or a single mapping). Passing a dictionary directly triggers the error:
query = "SELECT * FROM users WHERE id = %s AND name = %s"
params = {"id": 42, "name": "alice"}
cursor.execute(query, params) # TypeError in many DB-API drivers
Most DB-API drivers expect a sequence for positional placeholders (%s, ?Use a tuple instead: params = (42, "alice"). On top of that, ). If your driver supports named placeholders (%(name)s), then a dictionary is correct—but the placeholder syntax must match Easy to understand, harder to ignore. That alone is useful..
3. Unpacking a Dictionary into a Function Expecting Positional Arguments
def greet(first, last):
return f"Hello, {first} {last}"
user = {"first": "Ada", "last": "Lovelace"}
greet(*user) # TypeError: dict is not a sequence
The * operator attempts to iterate over the object as a sequence. Iterating a dictionary yields its keys, not key-value pairs, and the unpacking protocol expects a sequence. Use **user for keyword argument unpacking instead That alone is useful..
4. Misusing enumerate() or zip() with a Dictionary
While enumerate() and zip() accept any iterable, passing a dictionary directly iterates over keys:
data = {"a": 1, "b": 2}
list(enumerate(data)) # [(0, 'a'), (1, 'b')] — usually not what you want
list(zip(data, data.values())) # [('a', 1), ('b', 2)] — works but implicit
This doesn’t raise TypeError, but it’s a logical cousin: treating a mapping as a sequence of keys. Worth adding: items()for key-value pairs,data. values()for values,data.Consider this: be explicit: data. keys() for keys.
How to Fix It: Choose the Right Tool
| Goal | Correct Approach |
|---|---|
| Iterate over key-value pairs | for k, v in my_dict.items(): |
| Get a list of values | list(my_dict.values()) |
| Get a list of keys | list(my_dict.Consider this: keys()) |
| Pass to a function expecting a sequence | Convert explicitly: tuple(my_dict. values()) |
Use with random.choice() |
random.Day to day, choice(list(my_dict. Because of that, values())) |
| Format SQL with positional placeholders | Use a tuple: cursor. execute(sql, (val1, val2)) |
| Format SQL with named placeholders | Use a dict and %(name)s syntax: `cursor. |
Defensive Coding: Check Types When Necessary
If you’re writing a function that accepts either a sequence or a mapping, use collections.abc for strong type checking:
from collections.abc import Sequence, Mapping
def process_items(items):
if isinstance(items, Mapping):
items = items.values()
elif not isinstance(items, Sequence):
raise TypeError("Expected a sequence or mapping")
# Now safe to index, slice, etc.
return [item.
This avoids `TypeError` downstream and makes your API flexible.
## Conclusion
`TypeError: dict is not a sequence` is not a bug—it’s a feature. When you see this error, pause and ask: *Am I trying to use a dictionary like a list?Consider this: * The fix is almost always to be explicit about what you want: keys, values, or items. Python’s type system prevents you from accidentally treating a key-value mapping as an ordered, indexable collection. By understanding the distinction between sequences and mappings, you’ll write clearer, more predictable code—and spend less time debugging type mismatches.