How to create key or append an element to key?
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
When building a dictionary where values are lists, you need to handle the case where a key does not yet exist. Appending to a missing key raises KeyError. The cleanest solutions are collections.defaultdict(list), which auto-creates empty lists for new keys, and dict.setdefault(key, []).append(value), which initializes and appends in one call. Both eliminate the manual "check if key exists, create list if not, then append" pattern.
The Problem
The key "fruits" does not exist, so there is no list to append to.
Method 1: defaultdict(list) - Recommended
When you access data["fruits"] and it does not exist, defaultdict calls list() to create an empty list, stores it, and returns it. The .append() then works normally.
Method 2: dict.setdefault()
setdefault(key, default) returns the existing value if the key exists, or sets and returns the default if it does not. Chaining .append() adds to the returned list.
Method 3: Manual Check
Explicit but verbose. Use defaultdict or setdefault instead.
Method 4: Try/Except
This follows Python's "easier to ask forgiveness than permission" (EAFP) principle, but it is clumsier than setdefault for this use case.
Comparison
Creating Key or Incrementing a Counter
The same pattern applies to counters:
Creating Key or Adding to a Set
Real-World Example: Grouping Records
Nested defaultdict
Other Languages
JavaScript
Java
Ruby
Common Pitfalls
dict.fromkeys(keys, [])shares one list: All keys point to the same list object. Use{k: [] for k in keys}instead to create independent lists.- **
defaultdict(list)vsdefaultdict([])**:defaultdicttakes a callable.listis callable (creates[]).[]is not callable - raisesTypeError`. - Accessing
defaultdictcreates keys:if key in dis safe, butd[key]creates the key with a default value even if you only wanted to check. Usekey in dfor existence checks. - JSON serialization:
json.dumps()works withdefaultdict, but the default factory is lost. Convert todict()first if round-tripping matters. - Thread safety: Neither
defaultdictnorsetdefaultis atomic. In multi-threaded code, usethreading.Lockorconcurrent.futures.
Summary
- Use
defaultdict(list)for the cleanest auto-creating dictionary of lists - Use
dict.setdefault(key, []).append(value)when you want a plain dict with no imports - Never use
dict.fromkeys(keys, [])- all keys share the same list object - The pattern works with
set,int, or any callable as the default factory - In JavaScript use
??=, in Java usecomputeIfAbsent, in Ruby useHash.newwith a block
Related reading
- How to create only one copy of graph in tensorboard events file with custom tf.Estimator?
- How to Create Own HashMap in Java?
- How to create the most compact mapping n → isprimen up to a limit N?
- How to create ZeroMQ socket suitable both for sending and consuming?
- How to create module-wide variables in Python?
- How to create pandas output for custom transformers?
- How to Deal with Algorithm/Data Structures Problems in Interview Process?
- How to deal with array of string features in traditional machine learning?

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.