Deep compare dict python

How to compare two dictionaries in Python

In this Python tutorial, we will understand how to check if two dictionaries are equal in Python. Here we will see how to compare dictionaries with one another and find if both are the same.

There are mainly 4 methods to check if two dictionaries are equal in Python. All 4 methods are listed and discussed below.

  1. Using == operator
  2. Using for loop
  3. Using list comprehension
  4. Using deepdiff

How to check if two dictionaries are equal in Python

Here we will discuss all 4 main methods to check if two dictionaries are equal in Python. And we start with the first basic method of using the == operator in Python.

Читайте также:  Java convert byte to float

Method 1: Check if two dictionaries are equal in Python using the == operator

One of the basic ways to compare two strings in Python is by using the == comparison operator in Python.

The == is a comparison operator in Python that we can use to check if two objects are equal or not in Python. Moreover, we can use this operator with Python Dictionary as well.

So, let us see an example of using the == operator with the dictionary.

# Define two dictionaries user_info1 = user_info2 = # Checking if the dictionaries are equal using the == operator if user_info1 == user_info2: print("Both dictionaries are equal") else: print("Both dictionaries are not equal")

In the above example, we have defined two dictionaries with the same data. And then we are comparing both the dictionaries using == operator and if statement.

And as both dictionaries are the same, we will get the following result.

Output: Both dictionaries are equal

However, let us change the value of any key from any of the dictionaries and compare again.

# Change one of the values in user_info2 user_info2['age'] = 25 # Check if the dictionaries are still equal using the == operator if user_info1 == user_info2: print("Both dictionaries are equal") else: print("Both dictionaries are not equal")

Here we modified the value of age from the user_info2 dictionary. And this time, as the dictionaries are not equal, we will get the following result.

Output: Both dictionaries are not equal

Method 2: Check if two dictionaries are equal in Python using for loop

  • In this method, we will use the dict.items() method to fetch the key and value of a dictionary separately.
  • Next, we will use the for loop to iterate over each key-value pair and use the if-else statement to compare if key-value pairs are the same in both dictionaries.

Here is an example of this approach in Python.

# Define two dictionaries user_info1 = user_info2 = # Compare the key-value pairs of the dictionaries using a for loop def compare_dict(dict1, dict2): for key, value in dict1.items(): if key in dict2 and dict2Deep compare dict python == value: continue else: print("Both dictionaries are not equal") break else: print("Both dictionaries are equal") # Calling the function to compare compare_dict(user_info1, user_info2)

In the above example, first, we defined two dictionaries, then we defined a function that will accept 2 dictionaries.

This function will use for loop with dict.items() method to iterate over each key-value pair. And within the loop, it uses the if statement to compare both keys and values.

In the last, the function returns a statement based on the dictionary comparison.

Output: Both dictionaries are equal

Now, let us change the value from one dictionary and compare both dictionaries again in Python.

# Change one of the values in user_info2 user_info2['age'] = 32 # Comparing again compare_dict(user_info1, user_info2)

Here is the result once the change value from the 2nd dictionary.

Output: Both dictionaries are not equal

Method 3: Check if two dictionaries are equal in Python using list comprehension

  • In this method, we will use the list comprehension method to fetch each key and value from both dictionaries.
  • After this, we are comparing values to check if both dictionaries are the same. This will result in forming a list of boolean values.
  • Now, to check if all the values in the list are TRUE, we will use the all() function on the boolean list. And based on this, we will conclude if both dictionaries are the same.

Here is an example of this approach in Python.

# Define two dictionaries job_counts1 = job_counts2 = # Check if the two dictionaries are equal using list comprehension def compare_dict(dict1, dict2): equal = all([dict1Deep compare dict python == dict2Deep compare dict python for key in dict1.keys() if key in dict2]) if equal: print("The job counts are equal.") else: print("The job counts are not equal.") # Calling function for compare dictionaries compare_dict(job_counts1, job_counts2)

In the above code, we are comparing two same dictionaries in Python. So, after execution, we will get the following result.

Output: The job counts are equal.

Let us test our function by changing certain values and comparing both dictionaries again.

# Change one of the values in job_counts2 job_counts2['Los Angeles'] = 1300 # Calling function for compare dictionaries compare_dict(job_counts1, job_counts2)

Now, as both dictionaries are not the same, we will get the following result in Python.

Output: The job counts are not equal.

Method 4: Check if two dictionaries are equal in Python using deepdiff

The deepdiff is a powerful library that helps to compare two Python objects and check if both objects are the same or not. This library also allows us to find the difference between both objects in Python.

However, to use this library first, we need to install this library in Python. For this, we will use the following command first.

Once we have installed this library successfully, we can follow the given example.

# Importing DeepDiff from deepdiff import DeepDiff # Define two dictionaries job_counts1 = job_counts2 = # Defining a function def compare_dict(dict1, dict2): # Check if the two dictionaries are equal using deepdiff diff = DeepDiff(dict1, dict2, ignore_order=True) if not diff: print("Both dictionaries are equal.") else: print("Both dictionaries are not equal.") # Calling function to compare dictionaries compare_dict(job_counts1, job_counts2)

In this example, we have defined a function named compare_dict() which will accept 2 dictionary values. And this function will use the DeepDiff class to compare both dictionaries and return a result based on it.

So, once we call the function and pass two same dictionaries to it, we will get the following result.

Check if two dictionaries are equal in Python

Additionally, we can also test this function by passing two different dictionaries to it.

# Change one of the values in job_counts2 job_counts2['Los Angeles'] = 1500 # Calling function to compare dictionaries compare_dict(job_counts1, job_counts2)

Here we modified the value for one dictionary and compared them using the compare_dict() function.

The result for the above execution is given below.

Output: Both dictionaries are not equal.

You may also like to read the following Python tutorials.

Conclusion

So, in this Python tutorial, we understood how to check if two dictionaries are equal in Python or not. And for this implementation in Python, we covered 4 different methods. These 4 methods are listed below.

  • Using == operator
  • Using for loop
  • Using list comprehension
  • Using deepdiff

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.

Источник

deepcomparer 0.4.0

Deep compare python structures like dictionaries, lists and iterables.

Ссылки проекта

Статистика

Метаданные

Лицензия: MIT License (MIT)

Метки compare, dictionary, list, array, deep, find, structure, nested, data

Требует: Python >=3.7

Сопровождающие

Классификаторы

Описание проекта

Deepcomparer

Deep compare python objects and structures like dictionaries, lists and iterables.

Getting Started

Installation

Usage

Подробности проекта

Ссылки проекта

Статистика

Метаданные

Лицензия: MIT License (MIT)

Метки compare, dictionary, list, array, deep, find, structure, nested, data

Требует: Python >=3.7

Сопровождающие

Классификаторы

История выпусков Уведомления о выпусках | Лента RSS

Загрузка файлов

Загрузите файл для вашей платформы. Если вы не уверены, какой выбрать, узнайте больше об установке пакетов.

Source Distribution

Uploaded 1 янв. 2023 г. source

Built Distribution

Uploaded 1 янв. 2023 г. py3

Хеши для deepcomparer-0.4.0.tar.gz

Хеши для deepcomparer-0.4.0.tar.gz
Алгоритм Хеш-дайджест
SHA256 c99a1fd328b350bbdfcf597f61e1cfb76d150c38dedf46ec709bf5eeeb7b88de Копировать
MD5 44a7cd1da39b7158103a89adc0d774f9 Копировать
BLAKE2b-256 4b3384a4de3c7081ea7132d6dcae54243ec56f1a77bb7f30f184f0fe7813ea73 Копировать

Хеши для deepcomparer-0.4.0-py3-none-any.whl

Хеши для deepcomparer-0.4.0-py3-none-any.whl
Алгоритм Хеш-дайджест
SHA256 89d92f2c14e0d7afc9451739fc1228a46028054182b1387a5710a7ad2cf4d46b Копировать
MD5 279df7a8c68a6a7aa5ddae4de8c2f05b Копировать
BLAKE2b-256 0063815fc0dacdd898cfa9e9145982fbac94160581170e6a5dc51cc0abe8b43c Копировать

Помощь

О PyPI

Внесение вклада в PyPI

Использование PyPI

Разработано и поддерживается сообществом Python’а для сообщества Python’а.
Пожертвуйте сегодня!

PyPI», «Python Package Index» и логотипы блоков являются зарегистрированными товарными знаками Python Software Foundation.

Источник

Check if two dictionaries are equal in Python

Dictionaries are a handy data type in Python, that allows you to work with key-value pairs, which can be retrieved either by their key or their value. In this post, we will learn how to check if two dictionaries are equal or not using multiple methods.

dict1 = dict2 = if dict1 == dict2: print("The dictionaries are equal") else: print("The dictionaries are not equal")
The dictionaries are not equal

Use == operator to check if the dictionaries are equal

The simplest technique to check if two or multiple dictionaries are equal is by using the == operator in Python. You can create the dictionaries with any of the methods defined in Python and then compare them using the == operator. It will return True the dictionaries are equals and False if not.

dict1 = dict(a=1, b=2, c=3) dict2 = dict(zip(['a', 'b', 'c'], [1, 2, 3])) dict3 = dict([('b', 2), ('a', 1), ('c', 3)]) dict4 = dict() # compare all dictionaries if dict1 == dict2 == dict3 == dict4: print('The dictionaries are equal') # compare two dictionaries if dict2 == dict4: print('The dictionaries are equal')
The dictionaries are equal The dictionaries are equal

Explanation of the above code example

  1. Created four dictionaries(dict1, dict2, dict3, dict4) using different methods.
  2. Using dict1 == dict2 == dict3 == dict4 code syntax we are comparing all the dictionaries. This will return True if all the dictionaries are equal.
  3. Using dict2 == dict4 code, we are comparing two dictionaries.
  4. Print message — «The dictionaries are equal» if the dictionaries are equal.

Compare dictionaries using the deepdiff python module

You can install the Python module deepdiff in your project and check the differences between the two dictionaries. We can install the deepdiff module using the below command in your project.

We will be using the DeepDiff() function from the deepdiff module to compare the dictionaries. It will return the dictionary that will contain the information of the difference between the dictionaries.

from deepdiff import DeepDiff dict1 = dict2 = result = DeepDiff(dict1, dict2) print(result)

Get common key-value pairs from two dictionaries

We can get the common key-value pairs from two dictionaries and check if those are equal or not. We will be using Python For loop to the common key-value pairs.

  1. Create two dictionaries that contain some properties.
  2. Create a blank dictionary that will contain the common key-value pairs.
  3. In each iteration of For Loop check if the key from the second dictionary exists in the first dictionary. Also, check if the value from both dictionaries is the same for the same key. If this condition is found true, add that key-value pair to the common dictionary variable.
dict1 = dict2 = common = <> for key in dict1: if ((key in dict2) and (dict1Deep compare dict python == dict2Deep compare dict python)): commonDeep compare dict python = dict1Deep compare dict python # print common key-value pairs print(common)

Источник

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