比较 Python 中的两个字典

Najwa Riyaz 2023年1月30日
  1. 在 Python 中使用 == 运算符比较两个字典
  2. 编写自定义代码来比较 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