Как сравнить значения в словаре python
Перейти к содержимому

Как сравнить значения в словаре python

  • автор:

Сравните два словаря на Python

Сравните два словаря на Python

В этой статье рассказывается, как сравнить два словаря в Python.

Please enable JavaScript

Используйте оператор == для сравнения двух словарей в Python

Оператор == в Python может использоваться для определения идентичности словарей или нет.

Вот пример, когда есть одинаковые словари.

Вот пример, когда есть неидентичные словари —

Вы можете сравнить множество словарей, как указано в следующем примере,

Напишите собственный код для сравнения двух словарей на Python

Вот как можно написать код для сравнения словарей и определения общего количества пар между словарями. Ниже приведены шаги.

Используйте цикл for для обхода каждого элемента в одном из словарей. Сравните каждый элемент этого словаря с другим словарем на основе общего индекса.
Если элементы равны, то поместите пару key:value в общий словарь результата.
После обхода всего словаря вычислите длину результирующего общего словаря, чтобы определить количество общих элементов между словарями.

Ниже приведен пример, демонстрирующий метод сравнения двух словарей в Python.

The Best Way to Compare Two Dictionaries in Python

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…


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.

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.

Mel's user avatar

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:

pfabri's user avatar

Daniel Myers's user avatar

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 .

Pedro Lobito's user avatar

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:


Sample code


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:

ssc's user avatar

Anubis's user avatar

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:

pfabri's user avatar

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.

Cloudkollektiv's user avatar

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».

MikeyE's user avatar

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.

user-asterix's user avatar

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

Есть ли лучший способ сравнить значения словаря

В настоящее время я использую следующую функцию для сравнения значений словаря. Есть ли более быстрый или лучший способ сделать это?

Редактировать: оба слова содержат одинаковые ключи.

8 ответов

Если у дикторов есть идентичные наборы ключей, и вам нужны все эти отпечатки для любой разницы в значениях, вы мало что можете сделать; может быть что-то вроде:

В значительной степени эквивалентно тому, что у вас есть, но вы можете получить более приятное представление, например, отсортировав diffkeys перед тем, как зацикливаться на нем.

Если вы просто сравниваете на равенство, вы можете просто сделать это:

В противном случае единственная серьезная проблема, которую я вижу, это то, что вы получите KeyError, если в dict1 есть ключ, которого нет в dict2, поэтому вы можете захотеть сделать что-то вроде этого:

Вы могли бы сжать это в понимание, чтобы просто получить список ключей, которые тоже не совпадают:

Единственная другая оптимизация, о которой я могу подумать, — это использовать len (dict), чтобы выяснить, в каком из dict меньше записей, и сначала пройти по нему, чтобы получить максимально короткий цикл.

Не уверен, что это помогает, но в моем приложении я должен был проверить, изменился ли словарь.

Выполнение этого не будет работать, так как в основном это все тот же объект:

Использование копий / копий работ:

Если истинная цель вопроса — сравнение между диктовками (а не печатные различия), ответ —

Это было упомянуто ранее, но я чувствовал, что это немного тонет в других битах информации. Это может показаться поверхностным, но сравнение значений у dicts действительно мощная семантика. Это покрывает

  • количество ключей (если они не совпадают, значения не совпадают)
  • имена ключей (если они не совпадают, они не равны)
  • значение каждого ключа (они также должны быть равны ‘==’)

Последний пункт снова кажется тривиальным, но на самом деле он интересен, поскольку означает, что все это применяется рекурсивно также к вложенным диктовкам. Например.

Подобная семантика существует для сравнения списков. Все это делает легким для вас, например, сравните глубокие структуры Json, наедине с простым «= info»>

Вы можете использовать наборы для этого тоже

Если ваши словари глубоко вложены и содержат разные типы коллекций, вы можете преобразовать их в строку json и сравнить.

Caveat — это решение может не работать, если в ваших словарях есть двоичные строки в значениях, так как это не json-сериализуемый

Хм, вы описываете dict1 == dict2 (проверьте, равны ли оба слова)

Но ваш код выполняет all( dict1[k]==dict2[k] for k in dict1 ) (проверьте, все ли записи в dict1 совпадают с записями в dict2)

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *