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

Slicing a dictionary in Python lets you create a smaller dictionary from a larger one. Unlike lists, dictionaries don't have a built-in slice operator, so you need different techniques.
In this article, you'll learn several techniques to slice dictionaries effectively. You will find practical tips, explore real-world applications, and get advice for debugging common errors you might encounter.
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 is a highly Pythonic way to slice a dictionary. It provides a concise syntax for creating a new dictionary by iterating over another collection—in this case, a list of keys you want to keep.
The expression {k: original_dict[k] for k in selected_keys} builds the new dictionary by performing a few quick steps:
- It loops through each key specified in the
selected_keyslist. - For each key, it finds the corresponding value within the
original_dict. - It then adds the key-value pair to the new
sliced_dict.
This method is efficient and very readable, making it a great choice when you have a predefined set of keys to extract.
Common dictionary slicing techniques
While dictionary comprehension is a powerful tool, you have other effective methods at your disposal, including using the dict() constructor, itertools.islice(), and conditional filtering.
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 is great when you need to slice a dictionary by position. It works by 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.
- First,
original_dict.items()retrieves all the key-value pairs. - The
list()function turns these pairs into a list of tuples. - The slice operator
[:3]selects the first three tuples from that list. - Finally, the
dict()constructor builds a new dictionary from the selected pairs.
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}
For a more memory-efficient approach, you can use itertools.islice(). Unlike creating a full list of items, islice() returns an iterator that yields elements on demand. This means it doesn't build a temporary copy in memory, which is a big advantage when you're working with large dictionaries.
- The expression
islice(original_dict.items(), 2, 4)slices the dictionary's items, starting at index 2 and stopping before index 4. - Finally, the
dict()constructor consumes the iterator to create the new dictionary.
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 applying a condition to its keys. This method uses a dictionary comprehension with an if clause to filter items based on your criteria. It's a flexible way to create a new dictionary containing only the elements you need.
- The expression iterates through each key-value pair from
original_dict.items(). - The
ifcondition checks if a key (k) meets certain criteria, like usingstartswith('b')orendswith('e'). - Only key-value pairs that satisfy the condition are included in the final dictionary.
Advanced dictionary slicing approaches
As you move beyond everyday slicing, you'll find advanced techniques that give you greater control over ordering, memory use, and value-based conditions.
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 (since version 3.7) remember insertion order, collections.OrderedDict explicitly guarantees it. This is especially useful when your code needs to run on older Python versions or when you want to make your intent for ordered data crystal clear.
- The code first converts the
original_dictinto anOrderedDictto ensure the item order is predictable. - It then gets the items, converts them to a list, and slices them using standard list slicing
[1:4]. - Finally, it creates a new
OrderedDictfrom the sliced items, preserving the predictable order.
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 efficient, dynamic representations of the dictionary's contents. Since you can't slice views directly, you first need to convert them into lists.
- The expression
list(original_dict.keys())creates a list of all keys. - You can then apply a slice like
[2:5]to get a specific range.
This technique 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 or positions; you can also filter a dictionary based on its values. This approach is perfect for when you need to partition data, such as separating items that meet a certain numeric condition. It gives you a powerful way to organize information dynamically.
- The code uses a dictionary comprehension to build new dictionaries from the original.
- An
ifcondition inside the comprehension checks each item's value (v) against a setthreshold. - This effectively splits the original dictionary into two new ones based on whether values are above or below the threshold.
Move faster with Replit
Replit is an AI-powered development platform that transforms natural language into working applications. Describe what you want to build, and Replit Agent creates it—complete with databases, APIs, and deployment.
For the dictionary slicing techniques we've explored, Replit Agent can turn them into production tools. For example, you could:
- Build a configuration manager that pulls specific settings from a large dictionary using a predefined list of keys.
- Create a data dashboard that dynamically filters items based on value thresholds, like separating high-priority tasks from low-priority ones.
- Deploy a data pagination utility that efficiently displays chunks of data from a large dataset using an iterator-based approach like
itertools.islice().
Describe your app idea, and Replit Agent writes the code, tests it, and fixes issues automatically, all in your browser.
Common errors and challenges
When slicing dictionaries, you might run into a few common roadblocks, but they're easy to navigate once you know what to look for.
Handling KeyError when slicing with non-existent keys
A KeyError is one of the most frequent issues you'll face. It happens when you try to access a key that doesn't exist in the dictionary, which is common when using a dictionary comprehension with a predefined list of keys. If a key from your list isn't in the target dictionary, your code will stop.
- You can prevent this by using the
get()method, which returnsNone(or a default value) for missing keys instead of raising an error. - Another way is to add a conditional check inside your comprehension, like
if k in original_dict, to ensure you only try to access keys that are actually there.
Debugging TypeError when mixing dictionary comprehension types
A TypeError often pops up when you try to perform an operation on a data type that doesn't support it. For instance, you can't directly slice dictionary view objects returned by methods like .keys() or .items(). Trying to do so, as in original_dict.items()[:3], will fail because views aren't lists.
The fix is straightforward: convert the view to a list before slicing it. By changing the expression to list(original_dict.items())[:3], you create a list that you can slice by position without any issues.
Avoiding RuntimeError when modifying dictionaries during iteration
Python throws a RuntimeError if you change a dictionary's size while iterating over it. This safety measure prevents unpredictable behavior that can arise from adding or removing items mid-loop. You can't, for example, loop through a dictionary's items and delete some of them in the same pass.
To work around this, you should iterate over a copy or create a new collection. You can build a new dictionary containing only the items you want to keep. Alternatively, you can create a separate list of keys to remove and then loop over that list to safely modify the original dictionary after your initial iteration is complete.
Handling KeyError when slicing with non-existent keys
A KeyError is a common roadblock when slicing dictionaries. It’s triggered when your code tries to access a key that doesn't exist in the source dictionary, which immediately stops execution. The following code demonstrates this exact problem in action.
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 fails because the selected_keys list includes 'date', which isn't a key in the original dictionary. Attempting to access this missing key immediately raises a KeyError. The following example shows how to handle this gracefully.
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)
The fix is to add a conditional check, if k in original_dict, inside the dictionary comprehension. This simple addition verifies that a key exists before your code attempts to access it, which gracefully sidesteps the KeyError. It’s a clean way to build a new dictionary while ignoring any keys that aren't in the original source. This is especially useful when your list of keys comes from an external source and might not be perfectly in sync.
Debugging TypeError when mixing dictionary comprehension types
A TypeError occurs when you try an operation on mismatched data types, like adding an integer to a string with the + operator. This often happens in dictionary comprehensions when values aren't uniform. The code below shows how this can break your program.
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)
The comprehension fails because you can't use the + operator to add an integer to a string value like '3'. This data type mismatch is what triggers the TypeError. The following example shows how to handle this gracefully.
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)
The fix adds a conditional check, if isinstance(v, int), to the dictionary comprehension. This ensures the operation v + 10 is only attempted on integer values, which prevents the TypeError. This error is common when you're working with dictionaries that might contain mixed data types. Be especially careful when your data comes from external sources like APIs or user input, where type consistency isn't always guaranteed.
Avoiding RuntimeError when modifying dictionaries during iteration
Modifying a dictionary while iterating over it triggers a RuntimeError in Python. This isn't a bug—it's a safeguard to prevent unpredictable outcomes. You can't add or remove items mid-loop without causing an error, as the following code demonstrates.
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 the dictionary while simultaneously attempting to remove elements from it using del original_dict[k]. This concurrent modification is what triggers the RuntimeError. The following example demonstrates a safe way to handle this operation.
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 fix is to iterate over a copy, not the original dictionary you're changing. This two-step process avoids the RuntimeError:
- First, a dictionary comprehension creates a new
filtered_dictcontaining the items to remove. - Then, you loop over the keys of this new dictionary to safely
delthem from the original.
This works because you're iterating over one collection while modifying another. Keep an eye out for this error whenever you need to clean up a dictionary based on its values inside a loop.
Real-world applications
Beyond debugging, dictionary slicing is essential for practical tasks like processing user data and analyzing complex, nested information.
Processing user data with dict slicing
Dictionary slicing is a practical way to handle user data, allowing you to extract just the essential information from complex profiles.
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 create a streamlined version of the original user_profiles data. It works in two main steps:
- The outer comprehension,
... for uid, profile in user_profiles.items(), loops through each user ID and their corresponding profile. - For each user, an inner comprehension builds a new, smaller dictionary containing only the
'name'and'city'from their profile.
This approach efficiently filters the nested data, giving you a new dictionary with just the essential contact details while discarding the rest.
Data analysis with nested dict filtering
You can also apply conditional filtering to nested dictionaries for data analysis, making it easy to isolate important trends like sales figures that exceed a certain target.
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 builds a new, filtered dictionary from the original sales_data. It efficiently sifts through each month's data to find specific information by:
- Iterating over each key-value pair using
sales_data.items(). - Using an
ifcondition to check whether the value for the'electronics'key is greater than 11,000. - Including only the months that meet this criterion in the new
high_electronics_salesdictionary, along with their sales figures.
It's a concise way to isolate key data points from a larger dataset.
Get started with Replit
Now, turn these slicing techniques into a real tool. Describe what you want to build, like "a config manager that extracts specific settings" or "a data utility that filters items above a certain price."
Replit Agent will write the code, test for errors, and deploy your app. Start building with Replit.
Create and 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.
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)