Python - 透過鍵交叉兩個字典
在本文中,我們將學習如何使用鍵交叉兩個字典。我們必須建立一個具有公共鍵的新字典。我們來看一個例子。
Input: dict_1 = {'A': 1, 'B': 2, 'C': 3} dict_2 = {'A': 1, 'C': 4, 'D': 5} Output: {'A': 1, 'C': 3}
我們將使用字典解析來解決此問題。按照以下步驟編寫程式碼。
- 初始化字典。
- 遍歷字典一,新增不存在於字典二中的元素。
- 列印結果。
示例
# initializing the dictionaries dict_1 = {'A': 1, 'B': 2, 'C': 3} dict_2 = {'A': 1, 'C': 4, 'D': 5} # finding the common keys result = {key: dict_1[key] for key in dict_1 if key in dict_2} # printing the result print(result)
如果你執行以上程式碼,則獲得以下結果。
輸出
{'A': 1, 'C': 3}
我們還可以使用按位 & 運算子解決這個問題。它只需過濾出字典中的公共鍵和相應的值。僅過濾具有相同值的鍵。
示例
# initializing the dictionaries dict_1 = {'A': 1, 'B': 2, 'C': 3} dict_2 = {'A': 1, 'C': 4, 'D': 5} # finding the common keys result = dict(dict_1.items() & dict_2.items()) # printing the result print(result)
如果你執行以上程式碼,則獲得以下結果。
輸出
{'A': 1}
總結
你可以根據自己的喜好和用例選擇任何想要的方法。如果你有任何疑問,可以在評論部分提出。
廣告