Python filter dict by value

Python dictionary filter + Examples

In this Python tutorial, we will discuss the Python dictionary filter. Here we will also cover the below examples:

  • Python dictionary filter keys
  • Python dictionary filter by value
  • Python dictionary filter none values
  • Python dictionary filter key based on value
  • Python filter dictionary from list
  • Python dictionary filter lambda
  • Python dict filter empty values

Python dictionary filter

  • Let us see how to filter a Dictionary in Python by using filter() function.
  • This filter() function will filter the elements of the iterable based on some function. So this filter function is used to filter the unwanted elements.

Here is the Syntax of the filter function

So this filter function will return the element from these iterables for which this function will become true. When this function will return true for any value of this iterable that value will be returned by this filter function.

Let’s take an example and check how to filter a Python dictionary.

my_dict = new_filt = dict(filter(lambda val: val[0] % 3 == 0, my_dict.items())) print("Filter dictionary:",new_filt)

Here is the Screenshot of the following given code

Python dictionary filter

Another example to check how to filter a dictionary in Python.

In this example, we have the even and odd number key elements in the dictionary. So if we want to filter only those elements whose values are even. In this case, check the condition if the key is even then add key-value pair to a new dictionary.

my_dict = Dictionary = dict() for (new_key, new_value) in my_dict.items(): if new_key % 2 == 0: Dictionary[new_key] = new_value print("Dictionary filter:",Dictionary)

Here is the Screenshot of the following given code

Python dictionary filter items function

Another example, how to filter a Python dictionary by using a simple loop.

Let’s take an example and check how to filter a dictionary

my_dict = loo_dict = dict() for new_ke, new_val in my_dict.items(): if new_ke%2 == 1: loo_dict[new_ke] = new_val print("Filter Dictionary",loo_dict)

In this example first, we will initialize a dictionary and store key-value pairs where the new_ke variable checks the condition if key%2==1).

Here is the Screenshot of the following given code

Python dictionary filter using simple loop

Python dictionary filter keys

  • Let us see how to filter keys in a Python dictionary.
  • By using for loop and dict.items() function to iterate through key-value pairs.
  • In this example use conditional statement to filter keys from dictionary. In this condition if key is bigger than 2 then it filters a new dictionary
Читайте также:  Фреймворк flask python примеры

Let’s take an example and check how to filter keys in a dictionary

new_Dict = to_dict = <> for key, value in new_Dict.items(): if (key > 2): to_dictPython filter dict by value = value print("Filtered Dictionary",to_dict)

Here is the screenshot of the following given code

Python dictionary filter keys

Another example to check how to filter keys in a dictionary by using the list comprehension method

In this example create a Python dictionary and assign them odd and even values as an argument. Now check if keys are even which means it is divisible by 2 using dict comprehension.

my_dict = filt_Dict = < key:value for (key,value) in my_dict.items() if key % 2 == 0>print("Filtered key:",filt_Dict)

Here is the Screenshot of the following given code

Python dictionary filter keys comprehension method

Python dictionary filter none values

  • Let us see how to filter a dictionary with none values in Python.
  • By using for loop method we have to execute a loop for all the keys and check for values if its none value then we have to append it into a list that stores all the keys.

Let’s take an example and check how to filter a dictionary with none values

my_dict = output = [] for element in my_dict: if my_dict[element] is None : output.append(element) print("None keys element : ",output)

Here is the Screenshot of the following given code

Python dictionary filter none values

How to filter a dictionary with none values

By using the filter and the Python lambda function we can easily check how to filter a dictionary with none values.

to_dictionary = dict(john = 8, lizeal = None, shane = 4, watson = None,george = 9) non_val = dict(filter(lambda item: item[1] is None, to_dictionary.items())) print(non_val)

Here is the Screenshot of the following given code

Python dictionary filter none values by filter method

Python dictionary filter key based on value

  • Let us see how to filter a key-based value in a Python dictionary.
  • By using Python list comprehension we can easily perform this task.
  • First we have to initializing the Python dictionary and get selective dictionary keys.

Let’s take an example and check how to filter a key based on the value

my_dict = value_list = ['George', 'Luis'] output = [my_dict[x] for x in value_list if x in my_dict] print ("values based keys : ",output)

Here is the screenshot of the following given code

Python dictionary filter key based on value

Another example to check how to filter a key-based value

By using dictionary comprehension we can check how to filter a key-based value in Python.

to_dict = sel_val = = 370> print(sel_val)

Here is the screenshot of the following given code

Python dictionary filter key based on value by dict

Python filter dictionary from list

  • Let us see how to filter a dictionary from list by using list comprehension method in Python.
  • In this example we will create a new list of dictionary and check the condition if the key is available in the list.

Let’s take an example and check how to filter a dictionary from the list.

new_list = [, , ] def condition(dic): return dic['john'] > 7 new_filt = [x for x in new_list if condition(x)] print(new_filt)

Here is the Screenshot of the following given code

Читайте также:  Check if string is md5 php

Python filter dictionary from list

Python dictionary filter lambda

  • Here we can see how to filter a dictionary using lambda function in Python.
  • lambda function are defined without a name, that’s why it is also called as anonymous function.
  • In this example we initialize a dictionary by containing elements whose values are string of length 8.

Let’s take an example and check how to filter a dictionary using the lambda function.

new_Dict = my_dict = dict(filter(lambda val: len(val[1]) == 5,new_Dict.items())) print(my_dict)

Here is the Screenshot of the following given code

Python dictionary filter lambda

This is how to filter a Python dictionary using lambda.

Python dict filter empty values

  • Here we can see how to filter a Python dictionary with empty values.
  • By using list comprehension we can easily check how to filter a dictionary with empty values.
my_dict = output = [] for element in my_dict: if my_dict[element] is None : output.append(element) print("Empty element : ",output)

Here is the Screenshot of the following given code

Python dict filter empty values

You may like the following Python tutorials:

In this Python tutorial, we will discuss the Python dictionary filter. Here we will also cover the below examples:

  • Python dictionary filter keys
  • Python dictionary filter by value
  • Python dictionary filter none values
  • Python dictionary filter key based on value
  • Python filter dictionary from list
  • Python dictionary filter lambda
  • Python dict filter empty values

I am Bijay Kumar, a Microsoft MVP in SharePoint. Apart from SharePoint, I started working on Python, Machine learning, and artificial intelligence for the last 5 years. During this time I got expertise in various Python libraries also like Tkinter, Pandas, NumPy, Turtle, Django, Matplotlib, Tensorflow, Scipy, Scikit-Learn, etc… for various clients in the United States, Canada, the United Kingdom, Australia, New Zealand, etc. Check out my profile.

Источник

Filter dictionary by value python – Python : Filter a dictionary by conditions on keys or values

BTech Geeks

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

Filter dictionary by value 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.

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 :

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

Читайте также:  Построить график плотности распределения python

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

#Program : #dictionary student_details= 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_detailsPython filter dict by value = value print("New dictionary:") print(new_student_details)

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 :

Filter dictionary 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= 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_detailsPython filter dict by value = value print("New dictionary:") print(new_student_details)

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

Filtering dictionary by key python: 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= 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)

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 :

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

#Program : #dictionary student_details= new_student_details=dict() #Iterate all over the items in dictionary new_dict = print("Filtered dictionary:") print(new_dict)

Output : Filtered dictionary:

Let’s overview the complete program :

#Program : #dictionary student_details= 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_detailsPython filter dict by value = 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 = print("Filtered dictionary:") print(filtered_dict)

Output: New dictionary: Filtered dictionary: Filtered dictionary:

Источник

Оцените статью