Slicing a dictionary
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
Python dictionaries do not support slicing with [start:stop] syntax like lists do. To extract a subset of a dictionary, use a dictionary comprehension with a set of desired keys: {k: d[k] for k in keys if k in d}. Alternatively, use operator.itemgetter for extracting values, or dict.items() with filtering for conditional slicing. Since Python 3.7+, dictionaries maintain insertion order, making position-based slicing possible via itertools.islice.
Slice by Keys (Most Common)
Slice by Position (Python 3.7+)
Since dictionaries maintain insertion order in Python 3.7+:
Slice by Value Condition
Exclude Keys (Inverse Slice)
Using operator.itemgetter
itemgetter extracts values (not key-value pairs) efficiently:
Nested Dictionary Slicing
Performance Comparison
For small subsets of a large dictionary, iterate over the desired keys and index into the dict. For large subsets, iterate over dict.items() and filter.
Common Pitfalls
- KeyError when indexing missing keys:
{k: d[k] for k in keys}raisesKeyErrorif any key is missing from the dictionary. Always addif k in dto the comprehension, or used.get(k, default)to provide a fallback value for missing keys. - Assuming dictionary order before Python 3.7: Position-based slicing with
islicerelies on insertion order, which is only guaranteed in Python 3.7+. In Python 3.6, CPython preserves order as an implementation detail but it is not part of the language spec. In Python 3.5 and earlier, dictionaries are unordered. - Modifying a dictionary while iterating:
for k in d: if condition: del d[k]raisesRuntimeError: dictionary changed size during iteration. Create a new dict with a comprehension instead of mutating the original. - Using
list(d.items())for large dictionaries: Converting all items to a list just to slice a few elements wastes memory. Useitertools.islice(d.items(), n)for lazy position-based slicing without materializing the full list. - Forgetting that
dict.keys()returns a view, not a list:d.keys()[0:3]raisesTypeErrorbecausedict_keysdoes not support indexing. Convert to a list first (list(d.keys())[0:3]) or useislice(d.keys(), 3).
Summary
- Use
{k: v for k, v in d.items() if k in keys}to slice by a set of keys - Use
itertools.islice(d.items(), start, stop)for position-based slicing (Python 3.7+) - Use value-based conditions in comprehensions for filtering:
{k: v for k, v in d.items() if v > threshold} - For small key subsets,
{k: d[k] for k in keys if k in d}is faster than scanning all items - Always guard against missing keys with
if k in dord.get(k, default)to avoidKeyError
Related reading
- Slow Performance with Apache Spark Gradient Boosted Tree training runs
- Smallest number that cannot be formed from sum of numbers from array
- SNS topic not publishing to SQS
- Solving a graph issue with Python
- Slicing a tensor by using indices in Tensorflow
- SockJS Python Client
- Solving Range Minimum Queries using Binary Indexed Trees Fenwick Trees
- Some followup questions about consistent hashing

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.