Filter list of dictionaries python

Filter a list of Python dictionaries by conditions

In this post, we are going to understand in Filter a list of Python dictionaries by conditions on keys or values. If we have a dictionary having huge data, it is better will filter the dictionary based on conditions.

1 . Filter a list of dictionaries by value

In this code example, we are filtering the dictionaries by value based on conditions. We have stud_dict, and we are filtering dictionaries key which has age ==20, We can change condition based on our requirment.

So the resulting output is only the dictionaries that pass given conditions on values. Here is the code example to understand this.

Code Example

#Program to filter a list of Python Dictionary stu_dict = [, , , ] student = [stu for stu in stu_dict if stu['age']==20] print('filtered dictionary based on key =\n',student)
filtered dictionary based on key = []

2.Filter list of dictionaries by key

In this code example, we are filtering the dictionaries by key based on conditions. We have stud_dict, and we are filtering dictionaries which have key name ‘sub’, We can change condition based on our requirment. So the resulting output is only the dictionaries that pass given condition on keys. Here is the code example to understand this.

filtered dictionary based on value = [, ]

3. Filter list of dictionaries based on multiple keys

In this code example, we have a list of keys (list_keys) to filter the dictionaries based on condition by multiples keys by using a list of comprehension. So we are filtering the list of dictionaries stu_dict.

Code Example

#Program to filter a list of Python Dictionary stu_dict = [, ,, ] #keys to filter list_keys = ['sub','age','name'] filter_dict = [ for ele in stu_dict] print('filtered dictionary based on mutiple keys =\n',filter_dict)
filtered dictionary based on multiple keys = [, , , <>]

4.filter list of dictionaries based on multiple keys using map()

In this code example, we have a list of keys (list_keys) to filter the dictionaries based on condition by multiples keys by using a list of comprehension. So we are filtering the list of dictionaries stu_dict.

Читайте также:  Html div при печати

Code Example

#Program to filter a list of Python Dictionary stu_dict = [, ,, ] #keys to filter list_keys = filter_Dict = list(map(lambda x: , stu_dict)) print('filtered dictionary based on mutiple keys =\n',filter_Dict)
filtered dictionary based on multiple keys = [, , , <>]

5. Filter() to filter a list of dictionaries by multiple values

In this code example, we are filtering the list of dictionaries by a list of values using the filter() method. We want to filter a dictionary that has key-value ==20 and the key name has value == Alice. If we need we can change the condition according to our requirements.As we can see in the output shows a list of dictionaries that satisfy the given condition

#Program to filter a list of Python Dictionary stu_dict = [, ,] #keys to filter list_keys = [20,'alice'] filter_Dict = list(filter(lambda d: d['age'] in list_keys, stu_dict)) print('filtered dictionary based on mutiple keys =\n',filter_Dict)
filtered dictionary based on mutiple keys = []

Conclusion

In this post, we have understood how to Filter a list of Python dictionaries by conditions on mutiple keys or values with code examples by using all these code examples we can easily filter a list of dictionaries.

Источник

Filter list of dictionaries python

Last updated: Feb 23, 2023
Reading time · 4 min

banner

# Table of Contents

# How to filter a List of Dictionaries in Python

To filter a list of dictionaries based on one or multiple values:

  1. Store the acceptable values in a list.
  2. Use a list comprehension to iterate over the list of dictionaries.
  3. Check if the specific key in each dictionary is equal to one of the acceptable values.
Copied!
list_of_dictionaries = [ 'id': 1, 'name': 'alice'>, 'id': 2, 'name': 'bobby'>, 'id': 3, 'name': 'carl'>, ] list_of_values = [1, 3] filtered_list_of_dicts = [ dictionary for dictionary in list_of_dictionaries if dictionary['id'] in list_of_values ] # 👇️ [, ] print(filtered_list_of_dicts)

filter list of dictionaries in python

We stored the acceptable values in a list and used a list comprehension to iterate over the list of dictionaries.

List comprehensions are used to perform some operation for every element or select a subset of elements that meet a condition.

On each iteration, we check if the current dictionary has an id key with one of the values in the list.

The in operator tests for membership. For example, x in l evaluates to True if x is a member of l , otherwise, it evaluates to False .

# Checking for a single value

If you only want to check for a single value, use the equality operator.

Copied!
list_of_dictionaries = [ 'id': 1, 'name': 'alice'>, 'id': 2, 'name': 'bobby'>, 'id': 3, 'name': 'carl'>, 'id': 4, 'name': 'bobby'>, ] filtered_list_of_dicts = [ dictionary for dictionary in list_of_dictionaries if dictionary['name'] == 'bobby' ] # 👇️ [, ] print(filtered_list_of_dicts)

checking for single value

The example checks if each dictionary has a name key with a value equal to bobby and returns the result.

The new list only contains the matching dictionaries.

# Filter a list of dictionaries using a for loop

You could also use a for loop to filter a list of dictionaries.

Copied!
list_of_dictionaries = [ 'id': 1, 'name': 'alice'>, 'id': 2, 'name': 'bobby'>, 'id': 3, 'name': 'carl'>, ] list_of_values = [1, 3] filtered_list_of_dicts = [] for dictionary in list_of_dictionaries: if dictionary['id'] in list_of_values: filtered_list_of_dicts.append(dictionary) # 👇️ [, ] print(filtered_list_of_dicts)

filter list of dictionaries using for loop

We used a for loop to iterate over the list of dictionaries.

On each iteration, we check if a certain condition is met.

# Filter a List of Dictionaries by unique values

To filter a list of dictionaries by unique values:

  1. Use a dict comprehension to iterate over the list.
  2. Use the value of each id property as a key and the dictionary as a value.
  3. Use the dict.values() method to only get the unique dictionaries.
  4. Use the list() class to convert the result to a list.
Copied!
list_of_dictionaries = [ 'id': 1, 'name': 'alice'>, 'id': 2, 'name': 'bobby'>, 'id': 1, 'name': 'carl'>, ] list_of_unique_dictionaries = list( dictionary['id']: dictionary for dictionary in list_of_dictionaries >.values() ) # 👇️ [, ] print(list_of_unique_dictionaries)

filter list of dictionaries by unique values

We used a dict comprehension to iterate over the list of dictionaries.

Dict comprehensions are very similar to list comprehensions.

They perform some operation for every key-value pair in the dictionary or select a subset of key-value pairs that meet a condition.

On each iteration, we set the value of the current id as the key and the actual dictionary as the value.

The keys in a dictionary are unique, so any duplicate values get filtered out.

We then use the dict.values() method to only return the unique dictionaries.

The dict.values method returns a new view of the dictionary’s values.

Copied!
my_dict = 'id': 1, 'name': 'bobbyhadz'> print(my_dict.values()) # 👉️ dict_values([1, 'bobbyhadz'])

The last step is to use the list() class to convert the view object to a list containing unique dictionaries.

# Filter a list of dictionaries based on a key

To filter a list of dictionaries based on a key:

  1. Use a list comprehension to iterate over the list of dictionaries.
  2. Use the dict.get() method to check if each dictionary contains the given key.
  3. The new list will only contain the dictionaries that contain the key.
Copied!
list_of_dictionaries = [ 'id': 1, 'name': 'alice'>, 'id': 2, 'name': 'bobby'>, 'id': 3, 'salary': 100>, ] filtered_list = [ dictionary for dictionary in list_of_dictionaries if dictionary.get('name') is not None ] # 👇️ [, ] print(filtered_list)

We used a list comprehension to iterate over the list of dictionaries.

On each iteration, we use the dict.get() method to check if the current dictionary contains the name key.

The dict.get method returns the value for the given key if the key is in the dictionary, otherwise a default value is returned.

The method takes the following 2 parameters:

Name Description
key The key for which to return the value
default The default value to be returned if the provided key is not present in the dictionary (optional)

If a value for the default parameter is not provided, it defaults to None , so the get() method never raises a KeyError .

The new list only contains the dictionaries that contain the given key.

# Additional Resources

You can learn more about the related topics by checking out the following tutorials:

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.

Источник

Python filter list of dictionaries

Python filter list of dictionaries

In the Python programming language, the dictionary is a data structure that allows users to access values by calling their key quickly. Today, our article will show you about Python filter list of dictionaries to speed up querying data.

What is the list of dictionaries?

A dictionary is an object that has one or many pairs of keys and values. People can access values through keys and vice versa. A list of dictionaries is a list having its elements as dictionary objects. For example:

myList = [, , ] print(type(myList)) # print(len(myList)) # 3 for i in myList: print(type(i)) #

We have a list named myList. The list has 3 elements, and all of them are dictionary objects.

Some methods for Python filter list of dictionaries

Filter by the values

In this example, suppose we have a list of dictionaries that contains the name and ages of some people, and we want to filter them based on their age. First, traverse the list to access the dictionaries. Then, in each dictionary, access the age value by calling the key “Age” and make a comparison.

data = [ , , , ] # Traverse the list for i in range(len(data)): # Access the values through the key and make a comparison if data[i]["Age"] < 35: print(data[i])

Filter by the keys

In this part, we will filter dictionaries based on their keys. In some cases, a few dictionaries will have different keys from others, and we will find them and print them out on the screen.

data = [ , , , ] # Traverse the list for i in range(len(data)): # Access the dictionary and find satisfying keys if "Unique" in data[i]: print(data[i])

Filter by access value of keys and values

It is possible that you have a list of dictionaries that have different keys. It is more complicated to access their values if you do not know their key. In this part, we will show you how to do that.

Also, we traverse the list in 2 parts above. But now, we will access the dictionaries by both keys and values through the items attribute and make a comparison.

data = [, , ] # Traverse the list for element in data: # Access the dictionaries by the items attribute for key, value in element.items(): if value < 35: print(element)

Summary

In summary, you can filter a list of dictionaries easily by flexibly accessing their keys and values. If the dictionaries have the same format of keys, access them with the keys. Else, access them by the items attribute. We hope you like this article about Python filter list of dictionaries.

Maybe you are interested:

My name is Robert Collier. I graduated in IT at HUST university. My interest is learning programming languages; my strengths are Python, C, C++, and Machine Learning/Deep Learning/NLP. I will share all the knowledge I have through my articles. Hope you like them.

Name of the university: HUST
Major: IT
Programming Languages: Python, C, C++, Machine Learning/Deep Learning/NLP

Источник

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