Python - 兩個字典中鍵值的差異
兩個 Python 字典在它們之間可能有一些公共鍵。在本文中,我們將研究如何獲得兩個給定字典中的鍵的差異。
用集合
這裡我們取兩個字典並對其應用集合函式。然後我們減去兩個集合以得出差異。我們透過兩種方式執行此操作,透過從第一個字典中減去第二個字典,然後從第二個字典中減去第一個字典。結果集會列出那些非公共的鍵。
示例
dictA = {'1': 'Mon', '2': 'Tue', '3': 'Wed'}
print("1st Distionary:\n",dictA)
dictB = {'3': 'Wed', '4': 'Thu','5':'Fri'}
print("1st Distionary:\n",dictB)
res1 = set(dictA) - set(dictB)
res2 = set(dictB) - set(dictA)
print("\nThe difference in keys between both the dictionaries:")
print(res1,res2)輸出
執行上述程式碼將為我們提供以下結果 -
1st Distionary:
{'1': 'Mon', '2': 'Tue', '3': 'Wed'}
1st Distionary:
{'3': 'Wed', '4': 'Thu', '5': 'Fri'}
The difference in keys between both the dictionaries:
{'2', '1'} {'4', '5'}在 for 迴圈中使用 in
另一種方法是,我們可以使用 for 迴圈遍歷一個字典的鍵,並使用 in 子句在第二個字典中檢查它的存在。
示例
dictA = {'1': 'Mon', '2': 'Tue', '3': 'Wed'}
print("1st Distionary:\n",dictA)
dictB = {'3': 'Wed', '4': 'Thu','5':'Fri'}
print("1st Distionary:\n",dictB)
print("\nThe keys in 1st dictionary but not in the second:")
for key in dictA.keys():
if not key in dictB:
print(key)輸出
執行上述程式碼將為我們提供以下結果 -
1st Distionary:
{'1': 'Mon', '2': 'Tue', '3': 'Wed'}
1st Distionary:
{'3': 'Wed', '4': 'Thu', '5': 'Fri'}
The keys in 1st dictionary but not in the second:
1
2
廣告
資料結構
網路
關係型資料庫管理系統
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP