Python – Cross mapping of Two dictionary value lists

PythonServer Side ProgrammingProgramming

When it is required to cross-map two dictionary valued lists, the ‘setdefault’ and ‘extend’ methods are used.

Example

Below is a demonstration of the same −

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)

Output

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]}

Explanation

  • Two dictionaries are defined and is displayed on the console.

  • They are sorted using ‘sorted’ method and lambda method and displayed on the console.

  • An empty dictionary is created.

  • The dictionary is iterated over, and the key is set to a default value.

  • The index of the elements in the second dictionary is obtained and added to empty dictionary using the ‘extend’ method.

  • This is the output that is displayed on the console.

raja
Published on 13-Sep-2021 07:35:34
Advertisements