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}
总结
你可以根据自己的喜好和用例选择任何想要的方法。如果你有任何疑问,可以在评论部分提出。
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP