Python
Dictionary
Programming
Data Structures
Coding Tips

Slicing a dictionary

Codemia Knowledge Hub ·

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)

python
1original = {'a': 1, 'b': 2, 'c': 3, 'd': 4, 'e': 5}
2
3# Extract specific keys
4keys_wanted = {'a', 'c', 'e'}
5subset = {k: v for k, v in original.items() if k in keys_wanted}
6print(subset)  # {'a': 1, 'c': 3, 'e': 5}
7
8# Alternative: index directly (faster for small key sets)
9subset = {k: original[k] for k in keys_wanted if k in original}
10
11# Using dict comprehension with a list of keys (preserves order)
12keys = ['c', 'a', 'e']
13subset = {k: original[k] for k in keys if k in original}
14print(subset)  # {'c': 3, 'a': 1, 'e': 5}

Slice by Position (Python 3.7+)

Since dictionaries maintain insertion order in Python 3.7+:

python
1from itertools import islice
2
3original = {'a': 1, 'b': 2, 'c': 3, 'd': 4, 'e': 5}
4
5# First 3 items
6first_three = dict(islice(original.items(), 3))
7print(first_three)  # {'a': 1, 'b': 2, 'c': 3}
8
9# Items 2-4 (0-indexed)
10middle = dict(islice(original.items(), 1, 4))
11print(middle)  # {'b': 2, 'c': 3, 'd': 4}
12
13# Last 2 items
14last_two = dict(islice(original.items(), len(original) - 2, len(original)))
15print(last_two)  # {'d': 4, 'e': 5}
16
17# Or convert to list for full slicing support
18items = list(original.items())
19last_two = dict(items[-2:])
20print(last_two)  # {'d': 4, 'e': 5}

Slice by Value Condition

python
1scores = {'alice': 85, 'bob': 92, 'charlie': 78, 'diana': 95, 'eve': 88}
2
3# Keep only scores above 85
4high_scores = {k: v for k, v in scores.items() if v > 85}
5print(high_scores)  # {'bob': 92, 'diana': 95, 'eve': 88}
6
7# Keep entries where key starts with a specific letter
8d_names = {k: v for k, v in scores.items() if k.startswith('d')}
9print(d_names)  # {'diana': 95}
10
11# Filter by both key and value
12result = {k: v for k, v in scores.items() if len(k) <= 3 and v > 80}
13print(result)  # {'bob': 92, 'eve': 88}

Exclude Keys (Inverse Slice)

python
1original = {'a': 1, 'b': 2, 'c': 3, 'd': 4, 'e': 5}
2
3# Remove specific keys
4exclude = {'b', 'd'}
5filtered = {k: v for k, v in original.items() if k not in exclude}
6print(filtered)  # {'a': 1, 'c': 3, 'e': 5}

Using operator.itemgetter

itemgetter extracts values (not key-value pairs) efficiently:

python
1from operator import itemgetter
2
3data = {'name': 'Alice', 'age': 30, 'city': 'NYC', 'role': 'engineer'}
4
5# Extract multiple values
6name, age, city = itemgetter('name', 'age', 'city')(data)
7print(name, age, city)  # Alice 30 NYC
8
9# Build a new dict from selected keys
10keys = ['name', 'role']
11subset = dict(zip(keys, itemgetter(*keys)(data)))
12print(subset)  # {'name': 'Alice', 'role': 'engineer'}

Nested Dictionary Slicing

python
1users = {
2    'user1': {'name': 'Alice', 'age': 30, 'email': '[email protected]'},
3    'user2': {'name': 'Bob', 'age': 25, 'email': '[email protected]'},
4    'user3': {'name': 'Charlie', 'age': 35, 'email': '[email protected]'},
5}
6
7# Extract specific fields from nested dicts
8names_and_ages = {
9    uid: {k: v for k, v in info.items() if k in {'name', 'age'}}
10    for uid, info in users.items()
11}
12print(names_and_ages)
13# {'user1': {'name': 'Alice', 'age': 30}, ...}
14
15# Filter outer dict by nested value
16over_30 = {uid: info for uid, info in users.items() if info['age'] > 30}

Performance Comparison

python
1import timeit
2
3d = {str(i): i for i in range(10000)}
4keys = {str(i) for i in range(0, 10000, 2)}  # Every other key
5
6# Dict comprehension with items() — scans all items
7timeit.timeit(lambda: {k: v for k, v in d.items() if k in keys}, number=1000)
8# ~2.5 ms per call
9
10# Dict comprehension indexing keys — faster when subset is small
11timeit.timeit(lambda: {k: d[k] for k in keys if k in d}, number=1000)
12# ~1.8 ms per call
13
14# For small key sets, direct indexing is fastest
15small_keys = ['0', '100', '500']
16timeit.timeit(lambda: {k: d[k] for k in small_keys}, number=1000)
17# ~0.002 ms per call

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} raises KeyError if any key is missing from the dictionary. Always add if k in d to the comprehension, or use d.get(k, default) to provide a fallback value for missing keys.
  • Assuming dictionary order before Python 3.7: Position-based slicing with islice relies 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] raises RuntimeError: 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. Use itertools.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] raises TypeError because dict_keys does not support indexing. Convert to a list first (list(d.keys())[0:3]) or use islice(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 d or d.get(k, default) to avoid KeyError

Course
Intermediate
27 lessons
15 hours
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 course
Data Structures & Algorithms practice on Codemia

Step through 300+ coding interview problems with animated visualisers that show the data structure changing as the code runs. The Blind 75 are free.

Practice algorithms