- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- 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 – All combinations of a Dictionary List
When it is required to display all the combinations of a dictionary list, a simple list comprehension and the ‘zip’ method along with the ‘product’ method are used.
Below is a demonstration of the same −
Example
from itertools import product my_list_1 = ["python", "is", "fun"] my_list_2 = [24, 15] print("The first list is :") print(my_list_1) print("The second list is :") print(my_list_2) temp = product(my_list_2, repeat = len(my_list_1)) my_result = [{key : value for (key , value) in zip(my_list_1, element)} for element in temp] print("The result is :") print(my_result)
Output
The first list is : ['python', 'is', 'fun'] The second list is : [24, 15] The result is : [{'python': 24, 'is': 24, 'fun': 24}, {'python': 24, 'is': 24, 'fun': 15}, {'python': 24, 'is': 15, 'fun': 24}, {'python': 24, 'is': 15, 'fun': 15}, {'python': 15, 'is': 24, 'fun': 24}, {'python': 15, 'is': 24, 'fun': 15}, {'python': 15, 'is': 15, 'fun': 24}, {'python': 15, 'is': 15, 'fun': 15}]
Explanation
The required packages are imported into the environment.
Two lists are defined and displayed on the console.
The cartesian product of the two lists is calculated using the ‘product’ method.
This result is assigned to a variable.
A list comprehension is used to iterate over the list, and the elements of first list and elements of previously defined variable are used to create a dictionary.
This is assigned to a variable.
This is the output that is displayed on the console.
Advertisements