比較 Python 中的兩個字典
Najwa Riyaz
2023年1月30日
本文將介紹如何在 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