Filter Dictionary Using String Values in Python

Filter Dictionary Using String Values In Python

The dictionary is a data type in Python. The dictionary is mutable, dynamic, and can be nested. The dictionary is always represented in the form of a key-value pair. Dictionaries can be filtered using a built-in method like ‘filter’. The filter function will help sort the dictionary according to keys or values. The dictionary can hold a large amount of data in a key-value form. We can perform different actions on the dictionary and access the data.

Later in this article, we will discuss the process of filtering dictionaries using the filter() function, type(), isinstance(), and dict() method.

Syntax Of Dictionary

My_Dictionary = { key : value }

In the above one-line code, the My_Dictionary variable contains the dictionary which is represented with the key and value enclosed in the curly brackets. The simple representation helps to create a dictionary.

Example 1: How to Use Dictionary

Take the example of creating a dictionary of the student’s grades. Every student is considered a key and the grades are considered a value. Let’s see the implementation.

Class ={ 'Snehal' : 'A', 'Riya' : 'B', 'Nitant' : 'A', 'Diya' : 'C' }
print(Class['Snehal'])

In this two-line code, the Class holds the dictionary. Line no. 1 contains all the key-value pairs of students and their grades. In line no. 2, the specific grade of the student is printed. For this, we need to use the name of the dictionary and then mention the key name inside the ‘[ ]’ brackets.

Dictionary Example 1
Dictionary Example 1

Here, in the output, we can see the grade of the student mentioned in the printing statement. In this way, we can access the value of any key if we define that key with the dictionary name inside the ‘[ ]’ brackets.

Filtering the Dictionaries with Filter Function.

The filter () function in Python is used for filtering the dictionaries. Technically, the filter() function is a built-in method in Python that can be paired with any function or data type. For example, Dictionary, List, Array, Tuples, etc.

Here, we are using this filter() function to filter out the key-value pairs from the dictionaries. The first step involves the initialization of the function with the condition. the second step includes the initialization of the dictionary with the key-value pair. The third step includes the use of the filter() function. Here, we need to add two parameters to the filter()function i.e. function with condition and the dict.items() method.

Use of Dict.items() Method in Python

Dict. item() method in Python is used to iterate through the dictionary. This dict.items() method gives output in the form of independent tuples(key-value pairs). So, we can apply functions or methods on every key-value pair. Let’s see one basic implementation of dict.items() method.

Class ={ 'Snehal' : 'A', 'Riya' : 'B', 'Nitant' : 'A', 'Diya' : 'C' }
Result = list(Class.items())
print(Result)

In the above block of code, Line No. 1 contains the ‘Class’ dictionary. dict.items() method is used in Line no. 2 with the item() function which helps to convert the tuples in the form of a list. Line No. 3 is a print statement.

Dict Items Method
Dict Items Method

In the output, the list of key-value pairs is represented as a tuple. Now, let’s try to implement the filter() function, dict.items() method to filter the dictionary using ‘key’.

Filtering ‘Key’ From Dictionary Using Filter() function in Python

Consider a simple example of the students and their grades. Here, the student’s name is the ‘key’ and the grade is ‘value’. If we want to filter out the dictionary for the student’s name then we will use the ‘key’ as a condition. Let’s try to understand this using code.

Class = { 'stu1' : 'A', 'stu2' : 'B', 'stu3' : 'A', 'stu4': 'C'}

def fun_for_filter(pairs):
    key,value = pairs
    filter_key = 'stu3'
    if key == filter_key:
        return True
    else:
        return False
        
Final_dic = dict(filter(fun_for_filter, Class.items()))
print(Final_dic)

In the code, the ‘Class’ dictionary is initialized on line No. 1. Line No. 3 to 9 contains the main body of our function that holds the condition. ‘filter_key’ variable hold the ‘key’ which is used to check the condition. A simple if-else statement is used to check ‘filter_key’. On line No. 10, the filter() function is applied to the dictionary and the result is printed.

Filter Function For Key 1
Filter Function For Key 1

In the output, we can see the dictionary which contains the grade of ‘stu3’. Here, the grades of ‘stu1’, ‘stu2’, and ‘stu4’ are filtered out from the original dictionary. In this manner, we can change the ‘filter_key’ to get the filtered dictionary.

Filtering ‘Value’ From Dictionary Using Filter() function in Python

Let’s take the same example to understand the process of filtering value from a dictionary. All the processes will remain the same but the conditions will be different this time. Instead of ‘key’ here we will use ‘value’ in condition statements. Let’s filter the dictionary for the students who got an ‘A’ grade in the examination.

Class = { 'stu1' : 'A', 'stu2' : 'B', 'stu3' : 'A', 'stu4': 'C'}

def fun_for_filter(pairs):
    key,value = pairs
    filter_value = 'A'
    if value == filter_value:
        return True
    else:
        return False
        
Final_dic = dict(filter(fun_for_filter, Class.items()))
print(Final_dic)

This code is similar to the previous one, the only difference is in line No. 5, the ‘filter_value’ variable contains the value ‘A’. This will filter out the dictionary for the students who got an ‘A’ grade in the examination. So, the final output should be the dictionary with the student’s name who got an ‘A’ grade.

Filter Function For Value 1
Filter Function For Value 1

In the output, we can see the correct results. The dictionary contains the name of students who got an ‘A’ grade in the examination.

How To Filter Dictionaries for Multiple Conditions?

What if we want to filter the dictionary for multiple conditions? Let’s see the process to execute multiple conditions for key-value pairs.

Filtering ‘keys’ From the Dictionary Using Filter() Function In Python

When we need to add multiple conditions, then providing a list of that conditions would be the best option. Here, we will assign the list of ‘keys’ so, these ‘keys’ will be excluded or included in the dictionary.

Class = { 'stu1' : 'A', 'stu2' : 'B', 'stu3' : 'A', 'stu4': 'C'}

def fun_for_filter(pairs):
    key,value = pairs
    filter_key = ['stu1','stu4']
    if key in filter_key:
        return True
    else:
        return False
        
Final_dic = dict(filter(fun_for_filter ,Class.items()))
print(Final_dic)

The ‘Filter_key’ variable is initialized on Line No. 5 which holds the list of conditions for this problem.

Filter Function For Multiple Key Condition
Filter Function For Multiple Key Condition In Dictionary

In the output image, the grades of stu1 and stu4 are printed because the list contains only these keys. The filtering process of the dictionary depends upon the condition provided in the list.

Filtering ‘Values’ From the Dictionary Using Filter() Function in Python

Here, we need to provide a list of the elements which contain values from the dictionary. Based on the conditions provided in the list we can filter out the dictionaries.

Class = { 'stu1' : 'A', 'stu2' : 'B', 'stu3' : 'A', 'stu4': 'C'}

def fun_for_filter(pairs):
    key,value = pairs
    filter_value = ['A', 'C']
    if value in filter_value:
        return True
    else:
        return False
        
Final_dic = dict(filter(fun_for_filter ,Class.items()))
print(Final_dic)

Lines No. 5 and 6 are changed in this example. This way, we can filter the dictionary with any values or keys.

Filter Function For Multiple Value Condition
Filter Function For Multiple Value Condition For dictionary

How To Use Type() Function For Filtering the Dictionary?

The dictionary may contain key-value pairs of different data types. These dictionaries with different data types can be filtered using the type() function and dictionary comprehension. The type() function is used to identify the type of key or value present in the dictionary. The dictionary may be represented in the form of integers and string values. For actual filtering, we are going to use dictionary comprehension but for the identification of integers, we need the type() function. Let’s see how these two different functions can work together to filter the dictionary as per our conditions.

sample_dictionary = {'stu1':'A', 'Roll_No': 7, 'class': 'D'}
result = {key : val for key, val in sample_dictionary.items()
                   if type(val) != int }
print(result)

The simple 3-line code is enough to filter the dictionary using the type() function and dictionary comprehension. The first line of code contains the initialization of the dictionary. This dictionary contains two different data types i.e. integer and string. Here, we are trying to filter out the dictionary which contains only string key-value pairs. For this, we have checked values and their data type. All integer values are excluded from the original dictionary. On line No. 4 we have printed new dictionary key-value pairs with the string data type.

Filter Dictionary Using Type Function
Filter Dictionary Using Type Function

We can see in the output image, the second key-value pair is excluded from the original dictionary because it is of integer data type.

How to Use Isinstance() Function For Filtering The Dictionary?

The best alternative to the type() function from the above example is the ‘isinstance()’ function. The role of the isinstance() function is the same as the type() function. Both are used to identify the data type of keys and values in the dictionary. This is also combined with the dictionary comprehension to print the new dictionary as an output. Let’s see the practical implementation of these functions.

sample_dictionary = {'stu1':'A', 'Roll_No': 7, 'class': 'D'}

result = {key : val for key, val in sample_dictionary.items()
                   if isinstance(val, int) }
print(result)

Line No. 1 contains the dictionary of combined data types. On line No. 2 the condition for values is mentioned with the use of the isinstance() function. This time we tried to filter out the dictionary only for integer data types. So, all the key-value pairs which contain integer data type will be reflected in the output as a dictionary.

Filter Dictionary Using Isinstance Function
Filter Dictionary Using Isinstance Function

The output is a dictionary that contains only integer values.

Summary

In this article, the topic of filtering dictionaries is explained in detail. The concepts like syntax and example of dictionary, filter() function for key-value pairs, filter() function for multiple key-value conditions, type() function, and isinstance() function with the dictionary comprehensions are thoroughly covered. Hope you will enjoy this article.

References

You can read more about the isinstance() function and type() function here.