Remove the First or Last item from a Dictionary in Python

avatar
Borislav Hadzhiev

Last updated: Apr 10, 2024
4 min

banner

# Table of Contents

  1. Remove the First item from a Dictionary in Python
  2. Remove the Last element from a Dictionary in Python
  3. Remove all keys except one from a Dictionary in Python

# Remove the first item from a Dictionary in Python

To remove the first item from a dictionary:

  1. Use the next() function to get the first key in the dictionary.
  2. Use the dict.pop() method to remove the first key from the dictionary.
main.py
a_dict = { 'site': 'bobbyhadz.com', 'topic': 'Python', 'id': 100 } first_key = next(iter(a_dict)) print(first_key) # ๐Ÿ‘‰๏ธ site first_value = a_dict.pop(first_key) print(first_value) # ๐Ÿ‘‰๏ธ bobbyhadz.com print(a_dict) # ๐Ÿ‘‰๏ธ {'topic': 'Python', 'id': 100}

remove first item from dictionary

The code for this article is available on GitHub

In the first example, we used the iter() function to get an iterator object from the dictionary's keys.

main.py
a_dict = { 'site': 'bobbyhadz.com', 'topic': 'Python', 'id': 100 } # ๐Ÿ‘‡๏ธ <dict_keyiterator object at 0x7fc0bbfbdad0> print(iter(a_dict)) first_key = next(iter(a_dict)) print(first_key) # ๐Ÿ‘‰๏ธ site

The next function returns the next item from the iterator.

If the dictionary is empty, the next() function would raise a StopIteration exception.

# Making sure the dictionary isn't empty before removing the item

You can use an if statement if you need to make sure the dictionary isn't empty before removing the first item.

main.py
a_dict = {} if len(a_dict) != 0: first_key = next(iter(a_dict)) print(first_key) # ๐Ÿ‘‰๏ธ site first_value = a_dict.pop(first_key) print(first_value) # ๐Ÿ‘‰๏ธ bobbyhadz.com

making sure the dictionary is not empty before removing the item

The code for this article is available on GitHub

We used the len() function to make sure the dictionary isn't empty before removing the first key.

# Remove the last element from a Dictionary in Python

Use the dict.popitem() method to remove the last element from a dictionary. The method removes and returns the last key-value pair from the dictionary.

main.py
a_dict = { 'site': 'bobbyhadz.com', 'topic': 'Python', 'id': 100 } last = a_dict.popitem() print(last) # ๐Ÿ‘‰๏ธ ('id', 100) print(last[0]) # ๐Ÿ‘‰๏ธ id print(last[1]) # ๐Ÿ‘‰๏ธ 100

remove last element from dictionary

The code for this article is available on GitHub

The dict.popitem() method removes and returns a (key, value) pair from the dictionary.

The key-value pair that was last added to the dictionary is returned first.

# Remove the first item from a Dictionary using del

You can also use the del if you need to just remove the key without retrieving the value.

main.py
a_dict = { 'site': 'bobbyhadz.com', 'topic': 'Python', 'id': 100 } first_key = next(iter(a_dict)) print(first_key) # ๐Ÿ‘‰๏ธ site del a_dict[first_key] print(a_dict) # ๐Ÿ‘‰๏ธ {'topic': 'Python', 'id': 100}

The del statement removes an item from a dictionary by key.

# Remove the last element from a Dictionary using dict.pop()

To remove the last element from a dictionary:

  1. Use the dict.keys() method to get a view of the dictionary's keys.
  2. Convert the view object to a list.
  3. Get the last key from the list.
  4. Use the dict.pop() method to remove the last element from the dictionary.
main.py
a_dict = { 'id': 1, 'site': 'bobbyhadz.com', 'topic': 'Python' } last_key = list(a_dict.keys())[-1] print(last_key) # ๐Ÿ‘‰๏ธ topic last_value = a_dict.pop(last_key) print(last_value) # ๐Ÿ‘‰๏ธ Python
The code for this article is available on GitHub

The dict.keys() method returns a new view of the dictionary's keys.

main.py
a_dict = { 'id': 1, 'site': 'bobbyhadz.com', 'topic': 'Python' } keys = a_dict.keys() print(keys) # ๐Ÿ‘‰๏ธ dict_keys(['id', 'site', 'topic'])

View objects cannot be accessed at a specific index, so we had to convert the view object to a list.

We then accessed the list at index -1 to get the last key.

The last step is to use the dict.pop() method to remove the last element from the dictionary.

The dict.pop() method removes the specified key and returns the corresponding value.

You can also use the reversed() function to get the last key in a dictionary.

main.py
a_dict = { 'id': 1, 'site': 'bobbyhadz.com', 'topic': 'Python' } last_key = next(reversed(a_dict.keys())) print(last_key) # ๐Ÿ‘‰๏ธ topic last_value = a_dict.pop(last_key, 'default value') print(last_value) # ๐Ÿ‘‰๏ธ Python

The reversed function takes an iterator, reverses it and returns the result.

The next() function returns the next item from the provided iterator.

# Remove all keys except one from a Dictionary in Python

To remove all keys except one from a dictionary:

  1. Declare a new variable and initialize it to a dictionary.
  2. Assign the key you want to keep and its value to the new dictionary.
main.py
a_dict = { 'id': 1, 'first': 'bobby', 'last': 'hadz', 'site': 'bobbyhadz.com', 'topic': 'Python' } key_to_keep = 'site' new_dict = {key_to_keep: a_dict[key_to_keep]} print(new_dict) # ๐Ÿ‘‰๏ธ {'site': 'bobbyhadz.com'}
The code for this article is available on GitHub

The first code sample removes all dictionary keys except one.

We basically create a new dictionary that only contains the key we want to keep.

This approach is much faster than iterating over the entire dictionary and checking if each key is the one to be kept.

# Remove all dictionary keys except multiple, specific keys

If you need to remove all dictionary keys except multiple, specific keys, use a dict comprehension.

main.py
a_dict = { 'id': 1, 'first': 'bobby', 'last': 'hadz', 'site': 'bobbyhadz.com', 'topic': 'Python' } keys_to_keep = ['first', 'site', 'topic'] new_dict = { key: a_dict[key] for key in keys_to_keep } # ๐Ÿ‘‡๏ธ {'first': 'bobby', 'site': 'bobbyhadz.com', 'topic': 'Python'} print(new_dict)
The code for this article is available on GitHub

We stored the keys we wanted to keep in a list and used a dict comprehension to iterate over the list of keys.

Dict comprehensions are very similar to list comprehensions.

They perform some operation for every key-value pair in the dictionary or select a subset of key-value pairs that meet a condition.

On each iteration, we return the current key and the corresponding value.

The new dictionary only contains the key-value pairs we want to keep.

# Additional Resources

You can learn more about the related topics by checking out the following tutorials:

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.

Copyright ยฉ 2024 Borislav Hadzhiev