Python : Filter a dictionary by conditions on keys or values

How to filter a dictionary by conditions on keys or values in python ?

This article is about the filtration of a dictionary according to arbitrary condition on key or values or on both where key is the name and value is the content.

As we know in python we express a dictionary as a pair (key:value) where values can be any data type and keys can be string, number or tuple, values can repeat but keys must be unique and immutable.

Now, for better understanding take an example

We have a dictionary named student_details contains keys and values.

student_details={1: 'Name' , 2: 'RollNo' , 3: 'Collage_Name' , 4: 'Branch' , 5: 'Mobile_No' , 6: 'City' , 7: 'State' , 8: 'Pincode' , 9: 'Address' , 10: 'Registration_No'}

Here, int type elements are keys and string type elements are values

Student_details[1] = Name
Student_details[2] = RollNo
Student_details[3] = Collage_Name
Student_details[4] = Branch
Student_details[5] = Mobile_No
Student_details[6] = City
Student_details[7] = State
Student_details[8] = Pincode
Student_details[9] = Address
Student_details[10] = Registration_No

Method-1 : Filter a Dictionary by conditions :

Filter a Dictionary by keys in Python :

We can filter the above dictionary by condition like the keys are even or the keys are prime or keys are odd.

Let’s filter above dictionary by keeping only elements whose keys are odd.

#Program :

#dictionary
student_details={1: 'Name' , 2: 'RollNo' , 3: 'Collage_Name' , 4: 'Branch' , 5: 'Mobile_No' , 6: 'City' , 7: 'State' , 8: 'Pincode' , 9: 'Address' , 10: 'Registration_No'}
new_student_details=dict()
#Iterate all over the items in dictionary
for (key,value) in student_details.items():
#Conditional statement
#only keep keys which are odd
  if ((key % 2) != 0):
    new_student_details[key] = value

print("New dictionary:")
print(new_student_details)
Output:
New dictionary:
{1: 'Name', 3: 'Collage_Name', 5: 'Mobile_No', 7: 'State', 9: 'Address'}

Here, new_student_details is the null dictionary which contains the element whose key is odd by making iteration of the items of new_student_details. We can also filter a dictionary by value fields.
Note : Like that by giving any arbitrary condition to the original dictionary, we can get the required new dictionary.

Filter a Dictionary by values in Python :

Like keys, we can also filter the dictionary by putting the condition in values.

Let’s filter above dictionary by keeping only elelemnts whose values length >= 7.

#Program :

#dictionary
student_details={1: 'Name' , 2: 'RollNo' , 3: 'College_Name' , 4: 'Branch' , 5: 'Mobile_No' , 6: 'City' , 7: 'State' , 8: 'Pincode' , 9: 'Address' , 10: 'Registration_No'}
new_student_details=dict()
#Iterate all over the items in dictionary
for (key,value) in student_details.items():
#Conditional statement
#only keep values whose length >=7
  if ((len(value) >= 7)):
    new_student_details[key] = value

print("New dictionary:")
print(new_student_details)
Output :
New dictionary :
{3: 'College_Name, 5: 'Mobile_No, 8: 'Pincode', 9: 'Address', 10: 'Registration_No'}

Method-2 : Filter a Dictionary by filter() method :

As we all know python has many pre-define functions. So we can use pre-define function i.e filter() instead of making your own.

  • filter() method
    * It is a built-in function
    * Returns boolean values i.e True or False
    * Filtered through a function to test if the item is accepted or not.
    * An iterable sequence to be filtered

Let’s try filter() to do conditional filteration on the same dictionary by keeping the elements whose keys are divisible by 2 i.e

#Program :

#dictionary
student_details={1: 'Name' , 2: 'RollNo' , 3: 'Collage_Name' , 4: 'Branch' , 5: 'Mobile_No' , 6: 'City' , 7: 'State' , 8: 'Pincode' , 9: 'Address' , 10: 'Registration_No'}
new_student_details=dict()
#Checking the condition which keys are even
new_dict=dict(filter(lambda elem: elem[0] % 2 == 0,student_details.items()))

print("New dictionary:")
print(new_dict)
Output :
New dictionary :
{2: 'RollNo' , 4: 'Branch' ,  6: 'City' , 8: 'Pincode' , 10: 'Registration_No'}

Here we filtered elements based on the keys , similarly we can put conditions on values also and we can filter the dictionary.

Method -3 : Filter a Dictionary by Dict Comprehension :

Let’s try filteration of a dictionary by keeping the elements whose keys are divisible by 2 i.e

#Program :

#dictionary
student_details={1: 'Name' , 2: 'RollNo' , 3: 'Collage_Name' , 4: 'Branch' , 5: 'Mobile_No' , 6: 'City' , 7: 'State' , 8: 'Pincode' , 9: 'Address' , 10: 'Registration_No'}
new_student_details=dict()
#Iterate all over the items in dictionary
new_dict = {key: value for key, value in student_details.items() if key%2==0}
print("Filtered dictionary:")
print(new_dict)
Output :
Filtered dictionary:
{2: 'RollNo' , 4: 'Branch' ,  6: 'City' , 8: 'Pincode' , 10: 'Registration_No'}

Let’s overview the complete program :

#Program :

#dictionary
student_details={1: 'Name' , 2: 'RollNo' , 3: 'Collage_Name' , 4: 'Branch' , 5: 'Mobile_No' , 6: 'City' , 7: 'State' , 8: 'Pincode' , 9: 'Address' , 10: 'Registration_No'}
new_student_details=dict()
# Iterate over all the items in dictionary
for (key,value) in student_details.items():
#Conditional statement
#only keep keys which is divisible by 2
    if ((key % 2) != 0):
        new_student_details[key] = value

print("New dictionary:")
print(new_student_details)

#Filter check the key is even or not and pair to the new dictionary
new_dict=dict(filter(lambda elem: elem[0] % 2 == 0,student_details.items()))
print("Filtered dictionary:")
print(new_dict)

# Iterate over all the items in dictionary and check the key is even or not and pair to the filtered dictionary
filtered_dict = {key: value for key, value in student_details.items() if key%2==0}
print("Filtered dictionary:")
print(filtered_dict)
Output:
New dictionary:
{1: 'Name', 3: 'Collage_Name', 5: 'Mobile_No', 7: 'State', 9: 'Address'}
Filtered dictionary:
{2: 'RollNo', 4: 'Branch', 6: 'City', 8: 'Pincode', 10: 'Registration_No'}
Filtered dictionary:
{2: 'RollNo', 4: 'Branch', 6: 'City', 8: 'Pincode', 10: 'Registration_No'}