# Python – All combinations of a Dictionary List

PythonServer Side ProgrammingProgramming

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

Live Demo

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.

Published on 06-Sep-2021 08:37:48