
- 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 – 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.
- Related Questions & Answers
- Python – Inverse Dictionary Values List
- Python program to get all pairwise combinations from a list
- Python – Create dictionary from the list
- Python Program – Create dictionary from the list
- How to get a list of all the keys from a Python dictionary?
- How to get a list of all the values from a Python dictionary?
- Python – Limit the values to keys in a Dictionary List
- Python – Convert List to Index and Value dictionary
- How to check for redundant combinations in a Python dictionary?
- C++ Program to Generate All Possible Combinations of a Given List of Numbers
- Program to find list of all possible combinations of letters of a given string s in Python
- All pair combinations of 2 tuples in Python
- Python – Rows with all List elements
- Python program to find all the Combinations in a list with the given condition
- Python – Remove dictionary from a list of dictionaries if a particular value is not present
Advertisements