How to slice a dictionary in Python
Learn how to slice a dictionary in Python. Explore different methods, tips, real-world applications, and how to debug common errors.

You can slice a Python dictionary to extract specific key-value pairs. Since dictionaries lack a built-in slice method, you'll need to use some clever workarounds to get the job done.
In this guide, you'll explore several techniques to slice dictionaries. You'll find practical tips, real-world applications, and debugging advice to help you select the right approach for your project.
Basic slicing with dictionary comprehension
original_dict = {'apple': 1, 'banana': 2, 'cherry': 3, 'date': 4, 'elderberry': 5}
selected_keys = ['apple', 'cherry', 'elderberry']
sliced_dict = {k: original_dict[k] for k in selected_keys}
print(sliced_dict)--OUTPUT--{'apple': 1, 'cherry': 3, 'elderberry': 5}
Dictionary comprehension offers a concise and Pythonic way to create a new dictionary based on an existing one. The expression {k: original_dict[k] for k in selected_keys} iterates through your list of desired keys.
For each key k in selected_keys, it finds the corresponding value in the original_dict and adds the key-value pair to the new dictionary. This method is efficient because it directly constructs the final dictionary without creating intermediate data structures, making your code both clean and performant.
Common dictionary slicing techniques
Beyond dictionary comprehension, other techniques offer more granular control, whether you're using the dict() constructor, slicing by position with itertools.islice(), or filtering keys by a specific condition.
Using dict() constructor with items()
original_dict = {'apple': 1, 'banana': 2, 'cherry': 3, 'date': 4, 'elderberry': 5}
# Extract first 3 key-value pairs
sliced_dict = dict(list(original_dict.items())[:3])
print(sliced_dict)--OUTPUT--{'apple': 1, 'banana': 2, 'cherry': 3}
This technique leverages the dict() constructor to slice a dictionary by position. It works by temporarily converting the dictionary's items into a list, which you can then slice just like any other list before converting it back into a dictionary.
- The
original_dict.items()method returns a view of the dictionary's key-value pairs as tuples. - Wrapping this in
list()creates a list from those tuples, allowing you to use standard list slicing like[:3]to grab the first three pairs. - Finally, the
dict()constructor rebuilds a new dictionary from your sliced list of tuples.
Using itertools.islice() for efficient extraction
from itertools import islice
original_dict = {'apple': 1, 'banana': 2, 'cherry': 3, 'date': 4, 'elderberry': 5}
sliced_dict = dict(islice(original_dict.items(), 2, 4))
print(sliced_dict)--OUTPUT--{'cherry': 3, 'date': 4}
The itertools.islice() function offers a memory-efficient way to slice any iterable, including dictionary items. Unlike standard list slicing, islice doesn't create a new list in memory. Instead, it returns an iterator that produces the desired items on demand, making it perfect for working with very large dictionaries.
- The expression
islice(original_dict.items(), 2, 4)takes the dictionary's items and extracts the elements from index 2 up to, but not including, index 4. - The
dict()function then takes this iterator and builds the new dictionary from the yielded key-value pairs.
Filtering dictionaries by key condition
original_dict = {'apple': 1, 'banana': 2, 'cherry': 3, 'date': 4, 'elderberry': 5}
sliced_dict = {k: v for k, v in original_dict.items() if k.startswith('b') or k.endswith('e')}
print(sliced_dict)--OUTPUT--{'banana': 2, 'date': 4}
You can also slice a dictionary by filtering its keys based on a specific condition. This approach uses a dictionary comprehension with an if clause to selectively build a new dictionary. It's a powerful way to extract data that matches a pattern rather than a fixed position or key name.
- The expression iterates through each key-value pair, represented as
kandv, from the original dictionary'sitems(). - The
ifcondition checks if a keykmeets your criteria—in this case, if it starts with 'b' usingstartswith('b')or ends with 'e' usingendswith('e'). - Only the key-value pairs that pass this test are included in the final dictionary.
Advanced dictionary slicing approaches
When the common techniques don't quite cut it, you can reach for advanced methods like collections.OrderedDict for predictable ordering or dynamic value-based slicing.
Using collections.OrderedDict for predictable ordering
from collections import OrderedDict
original_dict = {'apple': 1, 'banana': 2, 'cherry': 3, 'date': 4, 'elderberry': 5}
ordered_dict = OrderedDict(original_dict)
sliced_ordered_dict = OrderedDict(list(ordered_dict.items())[1:4])
print(sliced_ordered_dict)--OUTPUT--OrderedDict([('banana', 2), ('cherry', 3), ('date', 4)])
While standard Python dictionaries now preserve insertion order (since version 3.7), OrderedDict from the collections module makes this behavior explicit. It’s a dictionary subclass designed specifically for ordered operations, giving you confidence that your slices will always be predictable.
- The code first converts the dictionary into an
OrderedDictto lock in the item sequence. - It then gets the dictionary’s items using
.items(), converts them to a list, and applies a standard list slice like[1:4]. - Finally, a new
OrderedDictis created from the sliced key-value pairs.
Slicing with dictionary views
original_dict = {'apple': 1, 'banana': 2, 'cherry': 3, 'date': 4, 'elderberry': 5}
keys = list(original_dict.keys())[2:5]
values = list(original_dict.values())[2:5]
print(f"Keys: {keys}\nValues: {values}")--OUTPUT--Keys: ['cherry', 'date', 'elderberry']
Values: [3, 4, 5]
You can also slice a dictionary's keys and values separately using dictionary views. The .keys() and .values() methods return view objects, which are dynamic, iterable representations of the dictionary's contents. Since views don't support slicing directly, you first need to convert them into lists.
- The expression
list(original_dict.keys())[2:5]creates a list of keys and then slices it. - Similarly,
list(original_dict.values())[2:5]does the same for the values.
This approach is useful when you only need a portion of the keys or values, not an entirely new dictionary.
Dynamically slicing based on value thresholds
original_dict = {'apple': 1, 'banana': 2, 'cherry': 3, 'date': 4, 'elderberry': 5}
threshold = 3
above_threshold = {k: v for k, v in original_dict.items() if v >= threshold}
below_threshold = {k: v for k, v in original_dict.items() if v < threshold}
print(f"Above: {above_threshold}\nBelow: {below_threshold}")--OUTPUT--Above: {'cherry': 3, 'date': 4, 'elderberry': 5}
Below: {'apple': 1, 'banana': 2}
Slicing isn't just for keys. You can also filter a dictionary based on its values. This example uses dictionary comprehensions to partition the data into two new dictionaries around a dynamic threshold.
- The first comprehension creates a dictionary with items whose values are greater than or equal to the
threshold(v >= threshold). - The second one gathers all items with values strictly less than the
threshold(v < threshold).
This technique is great for segmenting data, like separating high-priority tasks from low-priority ones.
Move faster with Replit
Replit is an AI-powered development platform where you can go from learning a technique to building a complete application in one place. It comes with all Python dependencies pre-installed, so you can skip setup and start coding instantly. Describe what you want to build, and Agent 4 handles everything—from writing the code and connecting databases to deploying it live.
Instead of piecing together techniques like dictionary slicing, you can describe the app you want to build and let Agent take it from idea to working product. For example:
- A data dashboard that slices a large dictionary of metrics to display only the key performance indicators above a certain threshold.
- A configuration utility that extracts a specific subset of settings from a master configuration file based on a list of required keys.
- A log processor that filters and segments raw log data by dynamically checking for keys that start with 'error' or 'warning'.
Simply describe your app, and Replit will write the code, test it, and fix issues automatically, all within your browser.
Common errors and challenges
Slicing dictionaries is powerful, but you might hit a few common snags that are easy to sidestep with the right approach.
Handling KeyError when slicing with non-existent keys
A KeyError is one of the most frequent issues you'll face. It pops up when you try to access a dictionary key that doesn't exist. This often happens when you're slicing with a predefined list of keys, and one of them isn't in your target dictionary.
- To prevent this, you can use the
.get()method, which returnsNone(or a default value you specify) instead of raising an error. - Alternatively, you can check if a key exists with the
inoperator before you attempt to include it in your slice.
Debugging TypeError when mixing dictionary comprehension types
You might also encounter a TypeError if you try to slice a dictionary or its views as if they were lists. For example, running original_dict.items()[:3] will fail because the .items() method returns a view object, not a list, and views don't support slicing.
The fix is straightforward: always convert the view to a list before slicing. By wrapping it in the list() constructor—like list(original_dict.items())[:3]—you can slice it by index without any issues.
Avoiding RuntimeError when modifying dictionaries during iteration
A RuntimeError: dictionary changed size during iteration occurs if you modify a dictionary while looping over it. This can happen if your slicing logic involves iterating through a dictionary and removing or adding elements to that same dictionary inside the loop.
To avoid this, don't modify the dictionary you're iterating over. Instead, iterate over a copy of its keys or items, or build a completely new dictionary with your filtered results. This ensures the iterator doesn't get confused by a changing data structure.
Handling KeyError when slicing with non-existent keys
A KeyError is a frequent issue you'll run into when slicing with a list of keys, especially if one key isn't in the dictionary. This error halts your program immediately. The code below shows what happens when you try this.
original_dict = {'apple': 1, 'banana': 2, 'cherry': 3}
selected_keys = ['apple', 'cherry', 'date'] # 'date' doesn't exist
sliced_dict = {k: original_dict[k] for k in selected_keys}
print(sliced_dict)
The comprehension attempts to access original_dict['date'], but since the key 'date' isn't present, Python raises a KeyError. Check out the following snippet for a robust way to handle this.
original_dict = {'apple': 1, 'banana': 2, 'cherry': 3}
selected_keys = ['apple', 'cherry', 'date'] # 'date' doesn't exist
sliced_dict = {k: original_dict[k] for k in selected_keys if k in original_dict}
print(sliced_dict)
To sidestep a KeyError, add a simple check directly within your dictionary comprehension. The condition if k in original_dict verifies that each key from your selected_keys list exists in the original dictionary before you try to access it. This makes your slicing operation more robust, especially when dealing with keys from external sources or user input. It’s a clean way to filter and slice simultaneously, ensuring your code runs without unexpected crashes.
Debugging TypeError when mixing dictionary comprehension types
A TypeError can sneak into your code when your dictionary contains mixed data types. If you try to perform an operation like addition on values that aren't compatible, such as a number and a string, your comprehension will fail. The following code demonstrates this.
original_dict = {'a': 1, 'b': 2, 'c': '3', 'd': 4}
numeric_dict = {k: v + 10 for k, v in original_dict.items()}
print(numeric_dict)
This code triggers a TypeError because the + operator can't add an integer like 10 to a string like '3'. The operation fails when types are incompatible. Check out the snippet below for a more robust approach.
original_dict = {'a': 1, 'b': 2, 'c': '3', 'd': 4}
numeric_dict = {k: v + 10 for k, v in original_dict.items() if isinstance(v, int)}
print(numeric_dict)
To prevent a TypeError, you can add a condition to your comprehension. The expression if isinstance(v, int) checks if a value is an integer before the operation is performed. This ensures your code only attempts arithmetic on compatible data types, sidestepping the error entirely.
It’s a crucial check when working with dictionaries that contain mixed data types, especially when the data comes from external sources like APIs or user input.
Avoiding RuntimeError when modifying dictionaries during iteration
Avoiding RuntimeError when modifying dictionaries during iteration
A RuntimeError happens if you change a dictionary's size while iterating over it. Python gets confused because the collection it's looping through is being altered mid-loop. This often occurs when deleting items from a dictionary inside a for loop.
The code below demonstrates what happens when you modify a dictionary while iterating over its items.
original_dict = {'a': 1, 'b': 2, 'c': 3, 'd': 4, 'e': 5}
filtered_dict = {}
for k, v in original_dict.items():
if v > 2:
filtered_dict[k] = v
del original_dict[k] # Modifies dict during iteration
print(filtered_dict)
The loop iterates over original_dict.items() while del original_dict[k] simultaneously tries to remove items from it. This modification during iteration triggers the RuntimeError. Check out the snippet below for a safer approach.
original_dict = {'a': 1, 'b': 2, 'c': 3, 'd': 4, 'e': 5}
filtered_dict = {k: v for k, v in list(original_dict.items()) if v > 2}
# Remove the filtered items from original_dict
for k in list(filtered_dict.keys()):
del original_dict[k]
print(filtered_dict)
The safest way to avoid a RuntimeError is to never modify a dictionary while iterating over it. The solution works by first creating a new dictionary with the filtered items. It then iterates over the keys of this new dictionary to safely delete items from the original. This two-step process ensures the collection you're looping through doesn't change size mid-iteration. It's a crucial pattern to use whenever you need to filter and remove items simultaneously.
Real-world applications
Moving past common errors, you'll find dictionary slicing is a go-to tool for tasks like processing user data and analyzing datasets.
Processing user data with dict slicing
In practice, you'll often use dictionary slicing to handle user data, selectively exposing only the necessary fields for a specific task like creating a contact directory.
user_profiles = {
'user1': {'name': 'John', 'age': 28, 'email': '[email protected]', 'city': 'New York'},
'user2': {'name': 'Lisa', 'age': 32, 'email': '[email protected]', 'city': 'Boston'},
'user3': {'name': 'Mike', 'age': 25, 'email': '[email protected]', 'city': 'Chicago'}
}
# Extract only names and cities for a contact directory
contact_info = {uid: {k: profile[k] for k in ['name', 'city']} for uid, profile in user_profiles.items()}
print(contact_info)
This example uses a nested dictionary comprehension to efficiently restructure the user_profiles data. It's a compact way to process dictionaries that contain other dictionaries as their values.
- The outer comprehension,
{uid: ... for uid, profile in user_profiles.items()}, loops through each user ID and profile dictionary. - For each user, the inner comprehension,
{k: profile[k] for k in ['name', 'city']}, builds a new, smaller dictionary containing only the specified keys.
This technique lets you create a clean, filtered version of your original data in a single expression.
Data analysis with nested dict filtering
For data analysis, dictionary slicing lets you filter nested data to pull out key insights, like identifying which months had the highest sales.
sales_data = {
'Jan': {'electronics': 10500, 'clothing': 8200},
'Feb': {'electronics': 9800, 'clothing': 6400},
'Mar': {'electronics': 11200, 'clothing': 9100},
'Apr': {'electronics': 9600, 'clothing': 8900},
'May': {'electronics': 12100, 'clothing': 10200},
'Jun': {'electronics': 13400, 'clothing': 11500}
}
# Extract months where electronics sales exceeded 11000
high_electronics_sales = {month: data['electronics']
for month, data in sales_data.items()
if data['electronics'] > 11000}
print(high_electronics_sales)
This dictionary comprehension efficiently filters the nested sales_data. It builds a new dictionary by checking a condition inside the inner data dictionary for each month.
- The
if data['electronics'] > 11000clause acts as a gatekeeper, only letting through months where electronics sales passed the 11,000 mark.
The resulting high_electronics_sales dictionary maps each qualifying month directly to its specific electronics sales figure, effectively extracting a targeted subset of the original data.
Get started with Replit
Turn your knowledge into a real tool. Describe what you want to build to Replit Agent, like “a utility to extract specific settings from a config file” or “a dashboard that filters user data by activity level.”
Replit Agent writes the code, tests for errors, and deploys your app from a single prompt. Start building with Replit.
Describe what you want to build, and Replit Agent writes the code, handles the infrastructure, and ships it live. Go from idea to real product, all in your browser.
Create & deploy websites, automations, internal tools, data pipelines and more in any programming language without setup, downloads or extra tools. All in a single cloud workspace with AI built in.

.png)
.png)
.png)