
- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Python – Cross mapping of Two dictionary value lists
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.
- Related Questions & Answers
- Python – Mapping Matrix with Dictionary
- Python - Ways to invert mapping of dictionary
- Convert two lists into a dictionary in Python
- Python – Dictionaries with Unique Value Lists
- In Python how to create dictionary from two lists?
- How to map two lists into a dictionary in Python?
- Python - Ways to create a dictionary of Lists
- Python – Replace value by Kth index value in Dictionary List
- Python – Convert List to Index and Value dictionary
- Python – Cross Join every Kth segment
- Python – Cross Pattern Pairs in List
- Python – Cross Pairing in Tuple List
- Python – Character indices Mapping in String List
- Intersection of Two Linked Lists in Python
- Adding two Python lists elements
Advertisements