Python - 两个词典值列表的交叉映射


要交叉映射两个词典值列表,可以使用“setdefault”和“extend”方法。

示例

以下是同一示例的演示:

Open Compiler
my_dict_1 = {"Python" : [4, 7], "Fun" : [8, 6]} my_dict_2 = {6 : [5, 7], 8 : [3, 6], 7 : [9, 8]} print("The first dictionary is : " ) print(my_dict_1) print("The second dictionary is : " ) print(my_dict_2) sorted(my_dict_1.items(), key=lambda e: e[1][1]) print("The first dictionary after sorting is ") print(my_dict_1) sorted(my_dict_2.items(), key=lambda e: e[1][1]) print("The second dictionary after sorting is ") print(my_dict_2) my_result = {} for key, value in my_dict_1.items(): for index in value: my_result.setdefault(key, []).extend(my_dict_2.get(index, [])) print("The resultant dictionary is : ") print(my_result)

输出

The first dictionary is :
{'Python': [4, 7], 'Fun': [8, 6]}
The second dictionary is :
{6: [5, 7], 8: [3, 6], 7: [9, 8]}
The first dictionary after sorting is
{'Python': [4, 7], 'Fun': [8, 6]}
The second dictionary after sorting is
{6: [5, 7], 8: [3, 6], 7: [9, 8]}
The resultant dictionary is :
{'Python': [9, 8], 'Fun': [3, 6, 5, 7]}

Learn Python in-depth with real-world projects through our Python certification course. Enroll and become a certified expert to boost your career.

说明

  • 定义了两个词典,并在控制台上显示。

  • 使用“sorted”方法和lambda方法对它们进行排序,并显示在控制台上。

  • 创建了一个空词典。

  • 对词典进行迭代,并将关键字设置为默认值。

  • 获取第二个词典中元素的索引,并使用“extend”方法将其添加到空词典中。

  • 这是在控制台上显示的输出。

更新于: 2021-09-13

536 次浏览

开启您的 职业生涯

完成课程,获得认证

开始
广告