Сравните два словаря на Python
Najwa Riyaz
30 Январь 2023
9 Июль 2021
-
Используйте оператор
==
для сравнения двух словарей в Python - Напишите собственный код для сравнения двух словарей на Python

В этой статье рассказывается, как сравнить два словаря в Python.
Используйте оператор ==
для сравнения двух словарей в Python
Оператор ==
в Python может использоваться для определения идентичности словарей или нет.
Вот пример, когда есть одинаковые словари.
dict1 = dict(name='Tom', Vehicle='Benz Car')
dict2 = dict(name='Tom', Vehicle='Benz Car')
dict1==dict2
Выход:
True
Вот пример, когда есть неидентичные словари -
dict1 = dict(name='John', Vehicle='Benz Car')
dict2 = dict(name='Tom', Vehicle='Benz Car')
dict1==dict2
Выход:
False
Вы можете сравнить множество словарей, как указано в следующем примере,
dict1 = dict(name='John', Vehicle='Benz Car')
dict2 = dict(name='Tom', Vehicle='Benz Car')
dict3 = dict(name='Shona', Vehicle='Alto Car')
dict4 = dict(name='Ruby', Vehicle='Honda Car')
dict1==dict2==dict3==dict4
Выход:
False
Напишите собственный код для сравнения двух словарей на Python
Вот как можно написать код для сравнения словарей и определения общего количества пар между словарями. Ниже приведены шаги.
-
Используйте цикл
for
для обхода каждого элемента в одном из словарей. Сравните каждый элемент этого словаря с другим словарем на основе общего индекса. -
Если элементы равны, то поместите пару
key:value
в общий словарь результата. -
После обхода всего словаря вычислите длину результирующего общего словаря, чтобы определить количество общих элементов между словарями.
Ниже приведен пример, демонстрирующий метод сравнения двух словарей в Python.
В этом случае словари идентичны.
dict1 = dict(name='Tom', Vehicle='Mercedes Car')
dict2 = dict(name='Tom', Vehicle='Mercedes Car')
dict1_len = len(dict1)
dict2_len = len(dict2)
total_dict_count=dict1_len+dict2_len
shared_dict = {}
for i in dict1:
if (i in dict2) and (dict1[i] == dict2[i]):
shared_dict[i] = dict1[i]
len_shared_dict=len(shared_dict)
print("The items common between the dictionaries are -",shared_dict)
print("The number of items common between the dictionaries are -", len_shared_dict)
if (len_shared_dict==total_dict_count/2):
print("The dictionaries are identical")
else:
print("The dictionaries are non-identical")
Выход:
The items common between the dictionaries are - {'name': 'Tom', 'Vehicle': 'Mercedes Car'}
The number of items common between the dictionaries are - 2
The dictionaries are identical
Затем давайте попробуем пример, когда словари не идентичны -
dict1 = dict(name='Tom', Vehicle='Alto Car')
dict2 = dict(name='Tom', Vehicle='Mercedes Car')
dict1_len = len(dict1)
dict2_len = len(dict2)
total_dict_count=dict1_len+dict2_len
shared_dict = {}
for i in dict1:
if (i in dict2) and (dict1[i] == dict2[i]):
shared_dict[i] = dict1[i]
len_shared_dict=len(shared_dict)
print("The items common between the dictionaries are -",shared_dict)
print("The number of items common between the dictionaries are -", len_shared_dict)
if (len_shared_dict==total_dict_count/2):
print("The dictionaries are identical")
else:
print("The dictionaries are non-identical")
Выход:
The items common between the dictionaries are - {'name': 'Tom'}
The number of items common between the dictionaries are - 1
The dictionaries are non-identical
Сопутствующая статья - Python Dictionary
- Как проверить наличие ключа в словаре на Python языке
- Как получить все файлы каталога
- Как сортировать Pythonский словарь по значению
- Как объединить два словаря на Python 2 и 3
- Как удалить элемент из словаря Pythonа
- Как получить ключи от словаря в виде списка на Python