Add WeChat " CNFeffery " to join the technical exchange group
❝
The complete sample code and files of this article have been uploaded to my
Github
repository https://github.com/CNFeffery/PythonPracticalSkills❞
This is the 10th issue of my series of articles "Python Practical Secrets"Python
. This series is based on the experience and experience accumulated by the author in my daily work. Each issue brings you a simple trick that can be learned in a few minutes.
As the 10th installment in the series, we're about to learn: deep comparison Python
of differences between objects.
In many cases, we need to compare the difference between two data. If it is only for numerical objects, then the difference between the two is the so-called difference, but what if we want to compare JSON
the difference between the two data?
Due to JSON
the characteristics of data that can be nested and layered, if you want to clearly find JSON
the difference between the two data and describe it, it is still a bit troublesome to write the method yourself. In this case, we can use deepdiff
a DeepDiff()
method in a third-party library, which is based on recursive deep comparison of different objects.
pip install deepdiff
After the installation is complete, you can directly compare the differences between the two objects by importing from deepdiff import DeepDiff
the required functions. JSON
The following is a simple example:
from deepdiff import DeepDiff
obj1 = {
'level1': [
{
'level1-1': 1,
'level1-2': 1,
'level1-3': [
{
'level1-3-1': [1, 2, 3]
}
]
}
],
'level2': 'a'
}
obj2 = {
'level1': [
{
'level1-1': 1,
'level1-2': 1,
'level1-3': [
{
'level1-3-1': [1, 2, 1]
}
]
}
],
'level2': 'b'
}
DeepDiff(obj1, obj2)
It can be seen that the difference content and specific location are specifically declared in the printed test results, which can help us carry out other subsequent processing.
In addition to this, deepdiff
there are very rich additional functions, such as ignoring comparison checks for data of a specified type:
Or by defining a hierarchy rule that DeepDiff()
skips the difference check for elements at specified positions:
It also supports the use of regular expressions to define fuzzy hierarchical rules to be ignored. For example, in the following example, we use regular batches to ignore multiple key-value pairs:
Limit the checking precision for floating-point numbers, such as in the following example, significant_digits=2
the difference after the second decimal point is ignored:
For more usage, interested readers and friends can move to https://zepworks.com/deepdiff/5.8.2/diff.html
learn more.
This sharing is over, see you next time~👋
Join Knowledge Planet [We Talk About Data Science]
500+ small partners to learn together!
· Recommended reading ·
Better function operation cache in Python
Not only fast, detailed explanation of the new version of geopandas file reading and writing