How to Remove First, Last, or Specific Items from Python Dictionaries
While dictionaries are primarily unordered collections, since Python 3.7, they remember the insertion order. This allows us to reliably remove the "first" or "last" inserted item.
This guide explores techniques for removing the first, last, or all but specific key-value pairs from a Python dictionary, leveraging its insertion order guarantee.
Removing the First Item (Insertion Order)
To remove the key-value pair that was first inserted into the dictionary (in Python 3.7+):
Using iter()
and next()
with pop()
(Recommended)
Get the first key using an iterator and then remove it with pop()
:
a_dict = {
'site': 'tutorialreference.com', # First inserted
'topic': 'Python',
'id': 100
}
if a_dict: # Check if dictionary is not empty
first_key = next(iter(a_dict))
print(f"Removing first key: {first_key}") # Output: Removing first key: site
first_value = a_dict.pop(first_key)
print(f"Removed value: {first_value}") # Output: Removed value: tutorialreference.com
else:
print("Dictionary is empty, can not remove first item.")
print(a_dict) # Output: {'topic': 'Python', 'id': 100}
iter(a_dict)
gets an iterator over the dictionary's keys (in insertion order).next(...)
retrieves the first key from the iterator.a_dict.pop(first_key)
removes the key-value pair and returns the removed value.- The
if a_dict:
check prevents errors on empty dictionaries.
Using iter()
and next()
with del
If you don't need the removed value, use the del
statement:
a_dict = {
'site': 'tutorialreference.com',
'topic': 'Python',
'id': 100
}
if a_dict:
first_key = next(iter(a_dict))
del a_dict[first_key] # Delete the key-value pair
print(a_dict) # Output: {'topic': 'Python', 'id': 100}
Removing the Last Item (Insertion Order)
Using dict.popitem()
(Python 3.7+ Recommended)
The popitem()
method is specifically designed to remove and return the last inserted key-value pair (LIFO - Last-In, First-Out) in Python 3.7+:
a_dict = {
'site': 'tutorialreference.com',
'topic': 'Python',
'id': 100 # Last inserted
}
if a_dict:
last_key, last_value = a_dict.popitem() # Removes and returns (key, value)
print(f"Removed last item: ({last_key}, {last_value})") # Output: Removed last item: ('id', 100)
print(a_dict) # Output: {'site': 'tutorialreference.com', 'topic': 'Python'}
- This is the most efficient and direct way to remove the last inserted item.
Using list(d.keys())[-1]
with pop()
You can manually get the last key and use pop()
:
a_dict = {
'id': 1,
'site': 'tutorialreference.com',
'topic': 'Python' # Last inserted
}
if a_dict:
last_key = list(a_dict.keys())[-1] # Get the last key
print(f"Removing last key: {last_key}") # Output: Removing last key: topic
last_value = a_dict.pop(last_key)
print(f"Removed value: {last_value}") # Output: Removed value: Python
print(a_dict) # Output: {'id': 1, 'site': 'tutorialreference.com'}
- This is less efficient than
popitem()
as it requires creating a list of all keys first.
Keeping Only Specific Keys (Creating a New Dictionary)
These methods create a new dictionary containing only the desired keys, leaving the original dictionary untouched.
Keeping a Single Key
Create a new dictionary directly with the key-value pair you want to keep:
a_dict = {
'id': 1,
'first': 'Tom',
'last': 'Nolan',
'site': 'tutorialreference.com',
'topic': 'Python'
}
key_to_keep = 'site'
# Use dict.get() for safety in case key_to_keep might not exist
if key_to_keep in a_dict:
new_dict = {key_to_keep: a_dict[key_to_keep]}
print(new_dict) # Output: {'site': 'tutorialreference.com'}
else:
print(f"Key '{key_to_keep}' not found in original dictionary.")
Keeping Multiple Keys (Dict Comprehension)
Use a dictionary comprehension to iterate through a list of keys you want to preserve:
a_dict = {
'id': 1,
'first': 'Tom',
'last': 'Nolan',
'site': 'tutorialreference.com',
'topic': 'Python'
}
keys_to_keep = ['first', 'site', 'topic']
# Create a new dict with only the specified keys
new_dict = {key: a_dict[key] for key in keys_to_keep if key in a_dict}
print(new_dict)
# Output: {'first': 'Tom', 'site': 'tutorialreference.com', 'topic': 'Python'}
- The comprehension iterates through
keys_to_keep
. if key in a_dict
ensures we only try to access keys that actually exist in the original dictionary, preventingKeyError
.
Important Note on Dictionary Order
- Remember that the concepts of "first" and "last" item rely on the insertion order preservation feature of dictionaries, which is guaranteed in Python 3.7 and later.
- In earlier Python versions (3.6 and below), dictionaries were unordered, and these methods would remove arbitrary items.
Conclusion
This guide demonstrated how to remove the first or last inserted items from Python dictionaries (version 3.7+) using next(iter(d))
, pop()
, and the highly recommended popitem()
.
- We also covered how to create new dictionaries containing only specific keys using direct creation or dictionary comprehensions.
- Always consider the Python version you are using, as dictionary order guarantees are relatively recent.