Сравните два словаря на Python
В этой статье рассказывается, как сравнить два словаря в Python.
Используйте оператор == для сравнения двух словарей в Python
Оператор == в Python может использоваться для определения идентичности словарей или нет.
Вот пример, когда есть одинаковые словари.
Вот пример, когда есть неидентичные словари —
Вы можете сравнить множество словарей, как указано в следующем примере,
Напишите собственный код для сравнения двух словарей на Python
Вот как можно написать код для сравнения словарей и определения общего количества пар между словарями. Ниже приведены шаги.
Используйте цикл for для обхода каждого элемента в одном из словарей. Сравните каждый элемент этого словаря с другим словарем на основе общего индекса.
Если элементы равны, то поместите пару key:value в общий словарь результата.
После обхода всего словаря вычислите длину результирующего общего словаря, чтобы определить количество общих элементов между словарями.
Ниже приведен пример, демонстрирующий метод сравнения двух словарей в Python.
Сравнение двух словарей в Python
у меня есть два словаря, но для упрощения я возьму эти два:
теперь я хочу сравнить, является ли каждый key, value в паре x имеет такое же соответствующее значение в y . Поэтому я написал следующее:
и он работает с tuple возвращается и затем сравнены для равенства.
это правильно? Есть ли лучше как это сделать? Лучше не в скорости, я говорю о коде изящество.
обновление: я забыл упомянуть, что я должен проверить, сколько key, value пар равны.
17 ответов:
Если вы хотите знать, сколько значений совпадают в обоих словарях, вы должны были сказать, что:)
может, что-то вроде этого:
что вы хотите сделать, это просто x==y
то, что вы делаете, не является хорошей идеей, потому что элементы в словаре не должны иметь никакого порядка. Вы можете сравнивать [(‘a’,1),(‘b’,1)] С [(‘b’,1), (‘a’,1)] (те же словари, разного порядка).
например, вижу так:
разница только один пункт, но ваш алгоритм будет видеть, что все предметы разные
Я новичок в python, но в итоге я сделал что-то похожее на @mouad
оператор XOR ( ^ ) следует исключить все элементы dict, когда они одинаковы в обоих dicts.
чтобы проверить, если два словаря имеют то же содержание, просто использовать:
С python docs:
чтобы проиллюстрировать, в следующих примерах все возвращают словарь, равный <"one": 1, "two": 2, "three": 3>:
ответ@mouad хорош, если вы предполагаете, что оба словаря просто содержат простые значения. Однако если у вас есть словари, которые содержат словари, вы получите исключение, поскольку словари не хэшируются.
С моей головы, что-то вроде этого может работать:
еще одна возможность, вплоть до последней ноты OP, заключается в сравнении хэшей ( SHA или MD ) из dicts сбрасывается как JSON. Способ построения хэшей гарантирует, что если они равны, исходные строки также равны. Это очень быстро и математически обоснованно.
-
deepdiff пакет должен быть установлен, как это не стандартный пакет
-
некоторые усилия должны быть приложены для разбора результат
чтобы проверить, равны ли два Дикта в ключах и значениях:
Если вы хотите вернуть значения, которые отличаются, пишут его по-разному:
вы должны были бы назвать его дважды т. е.
функция отлично ИМО, ясно и интуитивно. Но просто чтобы дать вам (еще один) ответ, вот мой:
может быть полезно для вас или для кого-либо еще..
вот еще вариант:
Так как вы видите, что два идентификатора отличаются. Но это богатые операторы сравнения кажется, сделать трюк:
В PyUnit есть метод, который сравнивает словари красиво. Я протестировал его с помощью следующих двух словарей, и он делает именно то, что вы ищете.
Я не рекомендую импорта unittest на ваш рабочий код. Моя мысль-источник в PyUnit может быть повторно использован для запуска в производство. Он использует pprint который «довольно печатает» словари. Кажется, довольно легко адаптировать этот код, чтобы быть «готов».
в Python 3.6, это можно сделать так:-
переменная ret будет истинной, если все элементы dict_1 присутствуют в dict_2
Comparing two dictionaries and checking how many (key, value) pairs are equal
I have two dictionaries, but for simplification, I will take these two:
Now, I want to compare whether each key, value pair in x has the same corresponding value in y . So I wrote this:
And it works since a tuple is returned and then compared for equality.
Is this correct? Is there a better way to do this? Better not in speed, I am talking about code elegance.
UPDATE: I forgot to mention that I have to check how many key, value pairs are equal.

28 Answers 28
If you want to know how many values match in both the dictionaries, you should have said that 🙂
Maybe something like this:
What you want to do is simply x==y
What you do is not a good idea, because the items in a dictionary are not supposed to have any order. You might be comparing [(‘a’,1),(‘b’,1)] with [(‘b’,1), (‘a’,1)] (same dictionaries, different order).
For example, see this:
The difference is only one item, but your algorithm will see that all items are different
dic1 == dic2
The following examples all return a dictionary equal to <"one": 1, "two": 2, "three": 3>:
Providing keyword arguments as in the first example only works for keys that are valid Python identifiers. Otherwise, any valid keys can be used.
Valid for python2 and python3 .
Since it seems nobody mentioned deepdiff , I will add it here for completeness. I find it very convenient for getting diff of (nested) objects in general:
Installation
Sample code
Output
Note about pretty-printing the result for inspection: The above code works if both dicts have the same attribute keys (with possibly different attribute values as in the example). However, if an «extra» attribute is present is one of the dicts, json.dumps() fails with
Solution: use diff.to_json() and json.loads() / json.dumps() to pretty-print:
Alternative: use pprint , results in a different formatting:
I’m new to python but I ended up doing something similar to @mouad
The XOR operator ( ^ ) should eliminate all elements of the dict when they are the same in both dicts.
@mouad ‘s answer is nice if you assume that both dictionaries contain simple values only. However, if you have dictionaries that contain dictionaries you’ll get an exception as dictionaries are not hashable.
Off the top of my head, something like this might work:
Yet another possibility, up to the last note of the OP, is to compare the hashes ( SHA or MD ) of the dicts dumped as JSON. The way hashes are constructed guarantee that if they are equal, the source strings are equal as well. This is very fast and mathematically sound.
The function is fine IMO, clear and intuitive. But just to give you (another) answer, here is my go:
Can be useful for you or for anyone else..
I have created a recursive version of the one above.. Have not seen that in the other answers
The easiest way (and one of the more robust at that) to do a deep comparison of two dictionaries is to serialize them in JSON format, sorting the keys, and compare the string results:
To test if two dicts are equal in keys and values:
If you want to return the values which differ, write it differently:
You would have to call it twice i.e
A simple compare with == should be enough nowadays (python 3.8). Even when you compare the same dicts in a different order (last example). The best thing is, you don’t need a third-party package to accomplish this.
I am using this solution that works perfectly for me in Python 3
It compares dict, list and any other types that implements the «==» operator by themselves. If you need to compare something else different, you need to add a new branch in the «if tree».
Hope that helps.
In PyUnit there’s a method which compares dictionaries beautifully. I tested it using the following two dictionaries, and it does exactly what you’re looking for.
I’m not recommending importing unittest into your production code. My thought is the source in PyUnit could be re-tooled to run in production. It uses pprint which «pretty prints» the dictionaries. Seems pretty easy to adapt this code to be «production ready».
Being late in my response is better than never!
Compare Not_Equal is more efficient than comparing Equal. As such two dicts are not equal if any key values in one dict is not found in the other dict. The code below takes into consideration that you maybe comparing default dict and thus uses get instead of getitem [].
Using a kind of random value as default in the get call equal to the key being retrieved — just in case the dicts has a None as value in one dict and that key does not exist in the other. Also the get != condition is checked before the not in condition for efficiency because you are doing the check on the keys and values from both sides at the same time.
Why not just iterate through one dictionary and check the other in the process (assuming both dictionaries have the same keys)?
This way you can subtract dictView2 from dictView1 and it will return a set of key/value pairs that are different in dictView2:
You can intersect, union, difference (shown above), symmetric difference these dictionary view objects.
Better? Faster? — not sure, but part of the standard library — which makes it a big plus for portability
The Best Way to Compare Two Dictionaries in Python
Learn how to check if two dictionaries are equal, assert for equality in unit tests, compare keys and values, take their dict diff, and more!
Play this article
Table of contents
When I had to compare two dictionaries for the first time, I struggled―a lot!
For simple dictionaries, comparing them is usually straightforward. You can use the == operator, and it will work.
However, when you have specific needs, things become harder. The reason is, Python has no built-in feature allowing us to:
- compare two dictionaries and check how many pairs are equal
- assert nested dictionaries are equal (deep equality comparison)
- find the difference between two dict s (dict diff)
- compare dict s that have floating-point numbers as values
In this article, I will show how you can do those operations and many more, so let’s go.
Why You Need a Robust Way to Compare Dictionaries
Let’s imagine the following scenario: you have two simple dictionaries. How can we assert if they match? Easy, right?
Yeah! You could use the == operator, off course!
That’s kind of expected, the dictionaries are the same. But what if some value is different, the result will be False but can we tell where do they differ?
Hum. Just False doesn’t tell us much.
What about the str ‘s inside the list . Let’s say that we want to ignore their cases.
What if the number was a float and we consider two floats to be the same if they have at least 3 significant digits equal? Put another way, we want to check if only 3 digits after the decimal point match.
You might also want to exclude some fields from the comparison. As an example, we might now want to remove the list key->value from the check. Unless we create a new dictionary without it, there’s no method to do that for you.
Yes, what if a value is a numpy array?
Oh no, it raises an exception in the middle of our faces!
Using the Right Tool for the Job
Since dict s cannot perform advanced comparisons, there are only two forms of achieving that. You can either implement the functionality yourself or use a third party library. At some point in your life you probably heard about not reinventing the wheel. So that’s precisely what we’re going to do in this tutorial.
We’ll adopt a library called deepdiff , from zepworks. deepdiff can pick up the difference between dictionaries, iterables, strings and other objects. It accomplishes that by searching for changes in a recursively manner.
deepdiff is not the only kid on the block, there’s also Dictdiffer, developed by the folks at CERN. Dictdiffer is also cool but lacks a lot of the features that make deepdiff so interesting. In any case, I encourage you to look at both and determine which one works best for you.
This library is so cool that it not only works with dictionaries, but other iterables, strings and even custom objects. For example, you can «even mix and match» and take the difference between two lists of dicts.
Getting a Simple Difference
In this example, we’ll be solving the first example I showed you. We want to find the key whose value differs between the two dict s. Consider the following code snippet, but this time using deepdiff .
Awesome! It tells us that the key ‘number’ had value 1 but the new dict , b, has a new value, 2.
Ignoring String Case
In our second example, we saw an example where one element of the list was in uppercase, but we didn’t care about that. We wanted to ignore it and treat «one» as «ONE»
You can solve that by setting ignore_string_case=True
If we don’t do that, a very helpful message is printed.
Comparing Float Values
We also saw a case where we had a float number that we only wanted to check if the first 3 significant digits were equal. With DeepDiff it’s possible to pass the exact number of digits AFTER the decimal point. Also, since float s differ from int ‘s, we might want to ignore type comparison as well. We can solve that by setting ignore_numeric_type_changes=True .
Comparing numpy Values
When we tried comparing two dictionaries with a numpy array in it we failed miserably. Fortunately, DeepDiff has our backs here. It supports numpy objects by default!
What if the arrays are different?
It shows that not only the values are different but also the types!
Comparing Dictionaries With datetime Objects
Another common use case is comparing datetime objects. This kind of object has the following signature:
In case we have a dict with datetime objects, DeepDiff allows us to compare only certain parts of it. For instance, if only care about year, month, and day, then we can truncate it.
Comparing String Values
We’ve looked at interesting examples so far, and it’s a common use case to use dict s to store strings values. Having a better way of contrasting them can help us a lot! In this section I’m going to explain you another lovely feature, the str diff.
That’s nice! We can see the exact lines where the two strings differ.
Excluding Fields
In this last example, I’ll show you yet another common use case, excluding a field. We might want to exclude one or more items from the comparison. For instance, using the previous example, we might want to leave out the text field.
If you want even more advanced exclusions, DeepDiff also allow you to pass a regex expression. Check this out: zepworks.com/deepdiff/current/exclude_paths…
Conclusion
That’s it for today, folks! I really hope you’ve learned something new and useful. Comparing dict ‘s is a common use case since they can used to store almost any kind of data. As a result, having a proper tool to easy this effort is indispensable. DeepDiff has many features and can do reasonably advanced comparisons. If you ever need to compare dict ‘s go check it out.