How to Remove Empty Keys From Dictionary Python

In this Python tutorial, I will demonstrate how to remove empty keys from the Python dictionary.

When data is collected from different sources, it is in Python dictionary form; when I analysed the data, I found that some of the keys were unnecessary and had empty values.

I used the Python loop to remove the unwanted empty keys from the collected data and cleaned it for further processing.

So, In this tutorial, I have explained how to remove or clean a dictionary with empty keys using the iterative method, dictionary comprehension, and single for loop.

Remove Empty Keys From Dictionary Python

First, let’s clarify the concepts of what empty keys mean. Empty keys represent the keys in a dictionary without value (or absence of value), for example, {‘age” “} or {‘age’:None}; here, keys themselves are not empty; instead, associated values are empty or null.

If you are confused with the term empty keys, or maybe you are thinking, instead of this {‘age’:” “}, it should be this {” “:21}. But according to my terminology, let’s say you have a box that contains something. If I say empty the box, you will take everything out of the box, and the box will become empty, so empty keys mean keys that have no value.

Let’s discuss different methods in Python to remove keys with empty values.

Python Remove Empty Keys From Dict

Create a dictionary user_data as shown below.

user_data = {
	"name": "Caleb",
	"age": 20,
	"email": "Caleb@gmail.com",
	"preferences": [],
  "alternate_email":None
}

Look at the dictionary containing two keys without value preferences and alternate_email. For some reason, these two keys don’t require any more in the dictionary user_data.

READ:  Python program to print the duplicate elements of an array [4 Methods]

To remove the empty keys from the dictionary user_data, you need to know which doesn’t have any value for create an empty list named key_no_value to store those keys, and then run the for loop to extract all the keys from the dict, which doesn’t have value.

key_no_value = []

for key, value in user_data.items():
  if value in [None, " ", {}, []]:
    key_no_value.append(key)

print("These are keys withou value", key_no_value)

In the above code, the key_no_value = []. This line creates an empty list named ‘key_no_value’, then ‘for key, value in user_data.items()’, It runs a loop and accesses the key-value pairs of the dictionary by calling items() on the user_data.

Then the next statement, ‘if value in [None, ” “, {}, []]’, checks if the current value is in the list or equal to ‘None, empty strings ” “, { } or [ ]’, if it is true, then the current value is empty, the corresponding key is added to the list ‘key_no_value’ by passing that key to append() method.

Now, the list key_no_value contains all the keys that have values like ‘None, {}, [], ” “‘, which is consters as empty.

Our task is to remove these keys, so again, run the for loop to remove these empty keys, as shown below.

for key in key_no_value:
  del user_data[key]

print('After removing empty keys:', user_data)
Python Remove Empty Keys From Dict

Look at the output, and it removes all the empty keys from the dictionary user_data.

Here, this line of code ‘for key in key_no_value: del user_data[key]’ takes each key from the list ‘key_not_value’, then deletes that key-value pairs using the del user_data[key].

READ:  Python Tkinter Window Size

Thus, it returns the final user_data dictionary without empty keys as {‘name’: ‘Caleb’, ‘age’: 20, ’email’: ‘Caleb@gmail.com’}.

This is how to remove empty keys from the dict in Python.

Python Remove Empty Keys From Dict Using Dictionary Comprehension

Dictionary comprehension is the shorter syntax to create a new dictionary based on the existing dictionary using the expression followed by the for loop within curly braces {}.

To remove the empty keys from the dictionary, take the same ‘user_data’ as in the above section.

user_data = {
	"name": "Caleb",
	"age": 20,
	"email": "Caleb@gmail.com",
	"preferences": [],
  "alternate_email":None
}
cleaned_user_data = {key:value for key ,value in user_data.items() if value not in [None, "", {}, []]}

print(cleaned_user_data)
Python Remove Empty Keys From Dict Using Dictionary Comprehension

Let’s understand the code part {key:value for key ,value in user_data.items() if value not in [None, “”, {}, []]}, this code part has three things, first is the ‘key:value’, the second is the loop ‘for key ,value in user_data.items()’, and the third is ‘if value not in [None, “”, {}, []]’.

Start with a loop ‘for key, value in user_data.items()’. You are already familiar with this line of code, which allows you to access each key-value pair of dictionary ‘user_data’ using the items() method.

Next, ‘if value not in [None, ” “, {}, []]’, checks each value is not in the list [None, ” “, {}, []] or the value of each key is not equal to the values in the [None, ” “, {}, []].

if the value doesn’t match with any of the empty values like in the list [None, “, {}, []], then the corresponding key with this value is included in the new dictionary cleaned_user_data.

As a result, in the dictionary cleaned_user_data, only the key with some value is included {‘name’: ‘Caleb’, ‘age’: 20, ’email’: ‘Caleb@gmail.com’}.

READ:  Python check if string contains substring [9 Methods]

Remove Keys with Empty Values Python Using For Loop

You can use the single for loop to remove keys with empty values by storing the keys with values in the new dictionary.

For example, let’s take the same ‘user_data’ and use it in the for loop, as shown in the code below.

user_data = {
	"name": "Caleb",
	"age": 20,
	"email": "Caleb@gmail.com",
	"preferences": [],
  "alternate_email":None
}

dict_without_empty_keys = {}

for key, value in user_data.items():
  if key and value:
    dict_without_empty_keys[key]=value

print("These are keys without value", dict_without_empty_keys)
Remove Keys with Empty Values Python Using For Loop

Look only using the single for loop. The keys with empty values have been removed from the dictionary ‘user_data’.

Here, understand this part of the code: ‘if key and value: dict_without_empty_keys[key]=value’. It checks if the key and value exist, and then it adds them to the dictionary dict_without_empty_keys.

In the conditional statement ‘if key and value’, both must be true; if either key exists or the value doesn’t, then it doesn’t add that key value to the dictionary, and vice versa.

This is how to remove keys with empty values in Python using a for loop.

Conclusion

In this Python tutorial, you learned how to remove empty keys from the Python dictionary using the for loop, iterative method and dictionary comprehension.

You may like to read: