How to remove None values from a dictionary in Python
In this tutorial, we will be learning the steps to be followed in order to remove None Values from a dictionary in Python. We’ll be using Pycharm IDE to solve this problem. We will be using items() function to detect a None value in the given dictionary.
Creating a Dictionary with Keys and Values
#Create a List keys = ["Name", "Age", "Country","Nothing"] #Convet List Into Keys d = dict.fromkeys(keys) print(d) #Give values to required Keys d['Name']='CodeSpeedy' d['Age']=18 d['Country']='India' print(d)
Output:
{‘Name’: None, ‘Age’: None, ‘Country’: None, ‘Nothing’: None}
{‘Name’: ‘CodeSpeedy’, ‘Age’: 18, ‘Country’: ‘India’, ‘Nothing’: None}
For Loop to remove keys with Value as None
items()
method is used to return the list with all dictionary keys with values.
We will be using a for loop to check if a value from the dictionary d matches with None. If the condition is true, then we simply delete the key that has None as its value.
#Using a for loop to remove keys with Value as None for key, value in dict(d).items(): if value is None: del d[key] print(d)
Complete Code
Here is the complete Python code to remove None values from a dictionary:
#Create a List keys = ["Name", "Age", "Country","Nothing"] #Convet List Into Keys d = dict.fromkeys(keys) print(d) #Give values to required Keys d['Name']='CodeSpeedy' d['Age']=18 d['Country']='India' print(d) #Using a for loop to remove keys with Value as None for key, value in dict(d).items(): if value is None: del d[key] print(d)
Give back “RuntimeError: dictionary changed size during iteration”
delete_me = []
for key, value in dict(d).items():
if value is None:
delete_me.append(key)
for key in delete_me:
del d[key]
# stupid, but it should work