Python creating a dictionary of lists
Data Structures & Algorithms practice on Codemia
Step through 300 algorithm problems with animated visualisers that show the data structure changing as the code runs.
Introduction
A dictionary of lists maps each key to a list of values, making it the go-to structure for grouping related items. The main challenge is handling the first value for a new key — you need to create the list before appending. Python provides several clean approaches: defaultdict(list), dict.setdefault(), and manual initialization. Each avoids the common KeyError trap.
The Problem: KeyError on First Append
The key "fruits" does not exist yet, so there is no list to append to. You must create the list first.
Method 1: defaultdict (Recommended)
collections.defaultdict automatically creates an empty list for any new key:
When you access groups["fruits"] and it does not exist, defaultdict calls list() to create an empty list, stores it, and returns it — all in one step.
Method 2: dict.setdefault()
setdefault(key, default) returns the existing value or sets and returns the default:
On the first call, setdefault creates the key with an empty list. On subsequent calls, it returns the existing list without replacing it.
Method 3: Manual Check
This is explicit but verbose. Prefer defaultdict or setdefault for cleaner code.
Method 4: Dictionary Comprehension
When you already have your data, build the dict-of-lists in one expression:
Method 5: Using itertools.groupby
For data that is already sorted by the grouping key:
groupby requires sorted input — consecutive items with the same key are grouped together.
Real-World Example: Grouping Records
Initializing with Known Keys
Nested Dictionaries of Lists
Converting to and from Other Formats
Common Pitfalls
- Mutable default argument trap:
dict.fromkeys(keys, [])makes all keys share the SAME list.d["a"].append(1)modifies every key. Use a comprehension:{k: [] for k in keys}. - defaultdict with wrong factory:
defaultdict(list)creates lists.defaultdict([])raisesTypeErrorbecause[]is not callable. The argument must be a callable likelist,set, orint. - Forgetting
groupbyneeds sorted input:itertools.groupbyonly groups consecutive matching elements. Sort the data first withsorted(data, key=...). - JSON serialization:
json.dumps(defaultdict(list))works, but the result loses the default factory. Convert to a regular dict first withdict(d)if you need to preserve the exact type. - Checking membership:
key in defaultdictdoes NOT create the key. Only accessingd[key]triggers the default factory. Usekey in dsafely for existence checks.
Summary
- Use
defaultdict(list)for the cleanest auto-initializing dict-of-lists - Use
dict.setdefault(key, []).append(value)when you want a plain dict - Never use
dict.fromkeys(keys, [])— all keys share the same list - Use dictionary comprehensions
{k: [] for k in keys}for pre-initialized dicts itertools.groupbyworks for already-sorted data- Convert
defaultdicttodict()before serializing to JSON
Related reading
- Python csv string to array
- Python data structure sort list alphabetically
- Python dataclass from a nested dict
- Python dictionary are keys and values always the same order?
- python dataframe pandas drop column using int
- python date of the previous month
- Python Dictionary Comprehension
- Python dictionary from an object's fields

DSA Fundamentals
Master algorithmic patterns and data structures through hands-on LeetCode-style problems - from arrays and hashing to dynamic programming and advanced graphs.
View the courseTrack what you have practised
A free account saves your progress, solutions and study plan across every problem on Codemia.
Data Structures & Algorithms practice on Codemia
Step through 300 algorithm problems with animated visualisers that show the data structure changing as the code runs.