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

更新於: 2020-7-22

3K+ 瀏覽

開啟你的職業生涯

完成課程即可獲得認證

開始
廣告
© . All rights reserved.