How To Delete a Set of Keys From a Python Dictionary


Estimated reading time: 2 minutes

In our last video on how to delete a key from a python dictionary, we illustrated where one key could be removed easily.

But what if you wanted to remove one or more keys?

How to delete more than one key from a Python dictionary

In the below code, we have created an empty dictionary. This will be populated by values in “dictionary_remove”.

Option1 uses the pop method :

  1. It creates an empty dictionary and then populates it with keys and values.
  2. Then it uses a loop to iterate over the list dictionary_remove.
  3. Then it looks at those and uses the pop method to find those values in the empty_dict1, and removes them

As a result, the following is what is returned:

Before:

{‘Key2’: ‘2’, ‘Key1’: ‘1’, ‘Key3’: ‘3’, ‘Key4’: ‘4’, ‘Key5’: ‘5’, ‘Key6’: ‘6’}

After:

{‘Key2’: ‘2’, ‘Key1’: ‘1’, ‘Key3’: ‘3’, ‘Key4’: ‘4’}

Option 2 uses the Del method :

In this second scenario, we do the following steps:

  1. We populate the dictionary_remove with two values, that are from the result of scenario 1 above.
  2. Then it uses a loop to iterate over the list dictionary_remove.
  3. Then it looks at those and uses the del method to find those values in the empty_dict1, and removes them

As a result, the following is what is returned:

Before:

{‘Key2’: ‘2’, ‘Key1’: ‘1’, ‘Key3’: ‘3’, ‘Key4’: ‘4’}

After:

{‘Key2’: ‘2’, ‘Key1’: ‘1’}

Slide 8
#How to delete more than one key from a dictionary
#1. Create a list to lookup against
empty_dict1 = {}

empty_dict1['Key2'] = '2'
empty_dict1['Key1'] = '1'
empty_dict1['Key3'] = '3'
empty_dict1['Key4'] = '4'
empty_dict1['Key5'] = '5'
empty_dict1['Key6'] = '6'

print(empty_dict1)

dictionary_remove = ["Key5","Key6"] # Lookup list

#1. Use the pop method

for key in dictionary_remove:
  empty_dict1.pop(key)
print(empty_dict1)

#2 Use the del method
dictionary_remove = ["Key3","Key4"]
for key in dictionary_remove:
  del empty_dict1[key]
print(empty_dict1)

We hope you enjoyed this, we have plenty of videos that you can look at to improve your knowledge of Python here: Data Analytics Ireland Youtube

Click here if you want to know how would you change the name of a key in a python dictionary as an alternative!

Leave a Reply

Your email address will not be published. Required fields are marked *