Horje
How to Compare List of Dictionaries in Python

The Python Dictionaries are a powerful data type in Python that allow you to store data as key-value pairs. In this article, we will be discussing how to compare elements in two dictionaries in Python. We will go over the syntax for comparing dictionary elements and will provide examples of how to do so.

What is a Dictionary?

The dictionary is a data structure similar to lists, tuples, and sets. A dictionary is used to store data or collections of items. A dictionary stores data in key-value pairs. A pair of braces generates an empty dictionary: {}. Placing a comma-separated list of key-value pairs between the braces adds the dictionary’s initial key-value pairs; this is also how dictionaries are written on output.

Depending on your goals, comparing lists of dictionaries in Python can include a variety of scenarios. Here are a few common approaches:

1. Comparing Entire Lists

To check if two lists of dictionaries are identical:

Python
# code
list1 = [{'id': 1, 'name': 'Ram'}, {'id': 2, 'name': 'Mohan'}]
list2 = [{'id': 1, 'name': 'Shyam'}, {'id': 2, 'name': 'sohan'}]

if list1 == list2:
    print("Lists are identical")
else:
    print("Lists are not identical")

Output:

Lists are not identical

2. Comparing List Elements

To find dictionaries that are present in both lists, you can use a list comprehension. This method checks each dictionary in the first list to see if it exists in the second list.

Python
# code
list1 = [{'id': 1, 'name': 'Ram'}, {'id': 2, 'name': 'Mohan'}]
list2 = [{'id': 2, 'name': 'Sohan'}, {'id': 3, 'name': 'Shyam'}]

common_dicts = [dict1 for dict1 in list1 if dict1 in list2]
print("Common dictionaries:", common_dicts)

Output:

Common dictionaries: []

3. Comparing Based on Specific Keys

To compare Sometimes, you may want to compare dictionaries based on specific keys, such as ‘id’. To do this, you can extract the values of these keys and compare them.based on specific keys (e.g., ‘id’):

Python
# code
list1 = [{'id': 1, 'name': 'Ram'}, {'id': 2, 'name': 'Mohan'}]
list2 = [{'id': 2, 'name': 'Sohan'}, {'id': 3, 'name': 'Shyam'}]

ids_list1 = {item['id'] for item in list1}
ids_list2 = {item['id'] for item in list2}

common_ids = ids_list1.intersection(ids_list2)
print("Common IDs:", common_ids)

Output:

Common IDs: {2}

In this example, common_ids will contain 2, which is the common ‘id’ between the two lists.

4. Custom Comparisons

or more complex comparisons, you might need custom logic. Here’s an example of how you can write a function to compare dictionaries with custom rules.

Python
# code
def compare_dicts(dict1, dict2):
    return dict1['id'] == dict2['id'] and dict1['name'].lower() == dict2['name'].lower()

list1 = [{'id': 1, 'name': 'Ram'}, {'id': 2, 'name': 'Mohan'}]
list2 = [{'id': 2, 'name': 'sohan'}, {'id': 3, 'name': 'Shyam'}]

common_dicts = [d1 for d1 in list1 for d2 in list2 if compare_dicts(d1, d2)]
print("Common dictionaries with custom comparison:", common_dicts)

Output:

Common dictionaries with custom comparison:

This output indicates that there are no dictionaries in list1 that exactly match a dictionary in list2 when considering both id and name with case-insensitive name comparison. The function correctly identifies no matches based on the given criteria.

Conclusion:

Comparing lists of dictionaries in Python can be done in various ways depending on what you need to achieve. Whether you need to check if two lists are identical, find common elements, or compare based on specific keys, Python provides the tools to do it efficiently. By using simple list comprehensions, set operations, or custom functions, you can handle any comparison scenario with ease.




Reffered: https://www.geeksforgeeks.org


Python

Related
How to Drop Negative Values in Pandas DataFrame How to Drop Negative Values in Pandas DataFrame
How to Import BeautifulSoup in Python How to Import BeautifulSoup in Python
How to Install BeautifulSoup in Anaconda How to Install BeautifulSoup in Anaconda
Remove Empty Dates from X Axis using Python Plotly Remove Empty Dates from X Axis using Python Plotly
How to Use lxml with BeautifulSoup in Python How to Use lxml with BeautifulSoup in Python

Type:
Geek
Category:
Coding
Sub Category:
Tutorial
Uploaded by:
Admin
Views:
15