Exclude specific keys from a Dictionary in Python

avatar

Borislav Hadzhiev

Last updated: Sep 15, 2022

banner

Photo from Unsplash

Exclude specific keys from a Dictionary in Python #

To exclude specific keys from a dictionary:

  1. Use the dict.items() method to get a view of the dictionary's items.
  2. Use a dict comprehension to iterate over the items.
  3. Exclude the specified keys from the dictionary.
main.py
my_dict = { 'id': 1, 'name': 'bobbyhadz', 'age': 30, 'language': 'python' } def exclude_keys(dictionary, keys): return { key: value for key, value in dictionary.items() if key not in keys } result = exclude_keys(my_dict, ['id', 'age']) print(result) # 👉️ {'name': 'bobbyhadz', 'language': 'python'} result = exclude_keys(my_dict, ['id', 'language']) print(result) # 👉️ {'name': 'bobbyhadz', 'age': 30}

The dict.items method returns a new view of the dictionary's items ((key, value) pairs).

main.py
my_dict = { 'id': 1, 'name': 'bobbyhadz', 'age': 30, 'language': 'python' } # 👇️ dict_items([('id', 1), ('name', 'bobbyhadz'), ('age', 30), ('language', 'python')]) print(my_dict.items())

We used a dict comprehension to iterate over the view.

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 use the not in operator to check if the current key is not in the list of keys to exclude.

main.py
def exclude_keys(dictionary, keys): return { key: value for key, value in dictionary.items() if key not in keys }

The in operator tests for membership. For example, x in l evaluates to True if x is a member of l, otherwise it evaluates to False.

x not in l returns the negation of x in l.

The exclude_keys function returns a new dictionary that doesn't contain the specified keys.

If you need to remove the keys from the original dictionary, use the dict.pop() method in a for loop.

main.py
my_dict = { 'id': 1, 'name': 'bobbyhadz', 'age': 30, 'language': 'python' } keys_to_remove = ['id', 'age'] for key in keys_to_remove: my_dict.pop(key, None) print(my_dict) # 👉️ {'name': 'bobbyhadz', 'language': 'python'}

We used a for loop to iterate over the keys to be removed.

On each iteration, we use the dict.pop() method to remove the key from the dictionary.

The dict.pop() method takes a default value to be returned if the specified key is not present in the dictionary.

If you don't provide a default value and the key is not in the dictionary, a KeyError is raised.

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.