Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
How to truncate a Python dictionary at a given length?
Truncating a dictionary in Python means limiting it to a fixed number of key-value pairs.
From version Python 3.7 onwards, dictionaries maintain insertion order, which makes it easy to slice and rebuild a smaller dictionary using the first N items. This is helpful when we want to reduce data size or process only a portion of the dictionary.
In this article, we explore different methods to truncate a Python dictionary at a given length.
Using itertools.islice() Method
The itertools.islice() method truncates a dictionary by slicing its items without loading all items into memory. This method is memory-efficient for large dictionaries.
Syntax
itertools.islice(sequence, stop) # or itertools.islice(sequence, start, stop, step)
Parameters
- sequence ? The item we want to iterate
- stop ? Stop the iteration at this position
- start ? Where the iteration begins (optional)
- step ? Skip items by this amount (optional)
Note: The islice() method does not support negative values for start, stop, or step.
Example 1: Truncate to First N Items
Here we truncate a dictionary to keep only the first 2 key-value pairs ?
import itertools
# Creating a Dictionary with 4 key-value pairs
product = {
"Product": "Mobile",
"Model": "XUT",
"Units": 120,
"Available": "Yes"
}
print("Original Dictionary:")
print(product)
# Truncating to first 2 items
truncated = dict(itertools.islice(product.items(), 2))
print("\nTruncated Dictionary:")
print(truncated)
Original Dictionary:
{'Product': 'Mobile', 'Model': 'XUT', 'Units': 120, 'Available': 'Yes'}
Truncated Dictionary:
{'Product': 'Mobile', 'Model': 'XUT'}
Example 2: Truncate in a Range
We can specify start and stop positions to extract items from a specific range ?
import itertools
# Creating a Dictionary with 6 key-value pairs
product = {
"Product": "Mobile",
"Model": "XUT",
"Units": 120,
"Available": "Yes",
"Grade": "A",
"Rating": "5"
}
print("Original Dictionary:")
print(product)
# Extract items from position 2 to 4 (indices 2, 3)
truncated = dict(itertools.islice(product.items(), 2, 4))
print("\nTruncated Dictionary (range 2-4):")
print(truncated)
Original Dictionary:
{'Product': 'Mobile', 'Model': 'XUT', 'Units': 120, 'Available': 'Yes', 'Grade': 'A', 'Rating': '5'}
Truncated Dictionary (range 2-4):
{'Units': 120, 'Available': 'Yes'}
Example 3: Truncate with Step
Use the step parameter to skip items while truncating ?
import itertools
product = {
"Product": "Mobile",
"Model": "XUT",
"Units": 120,
"Available": "Yes",
"Grade": "A",
"Rating": "5"
}
print("Original Dictionary:")
print(product)
# Start at index 1, stop at 5, step by 2 (take every 2nd item)
truncated = dict(itertools.islice(product.items(), 1, 5, 2))
print("\nTruncated Dictionary (step=2):")
print(truncated)
Original Dictionary:
{'Product': 'Mobile', 'Model': 'XUT', 'Units': 120, 'Available': 'Yes', 'Grade': 'A', 'Rating': '5'}
Truncated Dictionary (step=2):
{'Model': 'XUT', 'Available': 'Yes'}
Using List Slicing with items()
Another approach converts dictionary items to a list, slices it, then converts back to a dictionary. This method is simple but creates a temporary list in memory.
Syntax
dict(list(dictionary.items())[:n])
Where n is the number of key-value pairs to retain.
Example
Here we truncate a dictionary to keep only the first 2 items ?
# Original dictionary
data = {'name': 'Alice', 'age': 30, 'city': 'New York', 'country': 'USA'}
print("Original Dictionary:")
print(data)
# Truncate to first 2 items
truncated = dict(list(data.items())[:2])
print("\nTruncated Dictionary:")
print(truncated)
Original Dictionary:
{'name': 'Alice', 'age': 30, 'city': 'New York', 'country': 'USA'}
Truncated Dictionary:
{'name': 'Alice', 'age': 30}
Comparison of Methods
| Method | Memory Usage | Best For |
|---|---|---|
itertools.islice() |
Low (iterator) | Large dictionaries, complex slicing |
list() + slicing |
Higher (creates list) | Small dictionaries, simple syntax |
Conclusion
Use itertools.islice() for memory-efficient truncation of large dictionaries. For simple cases with small dictionaries, list slicing provides cleaner syntax. Both methods preserve insertion order in Python 3.7+.
