![]() |
VOOZH | about |
Given 2 lists, form all possible combination of dictionaries that can be formed by taking keys from list1 and values from list2.
Input : test_list1 = ["Gfg", "is", "Best"], test_list2 = [4]
Output : [{'Gfg': 4, 'is': 4, 'Best': 4}]
Explanation : All combinations dictionary list extracted.
Input : test_list1 = ["Gfg", "is", "Best"], test_list2 = [5, 6]
Output : [{'Gfg': 5, 'is': 5, 'Best': 5}, {'Gfg': 5, 'is': 5, 'Best': 6}, {'Gfg': 5, 'is': 6, 'Best': 5}, {'Gfg': 5, 'is': 6, 'Best': 6}, {'Gfg': 6, 'is': 5, 'Best': 5}, {'Gfg': 6, 'is': 5, 'Best': 6}, {'Gfg': 6, 'is': 6, 'Best': 5}, {'Gfg': 6, 'is': 6, 'Best': 6}]
Explanation : All combinations dictionary list extracted.
Method #1 : Using product() + dictionary comprehension + list comprehension
In this, we get all the combination possible using product() and dictionary comprehension generates each dictionary, list comprehension is used to iterate combinations generated.
Output:
The original list 1 is : ['Gfg', 'is', 'Best'] The original list 2 is : [4, 5] The combinations dictionary : [{'Gfg': 4, 'is': 4, 'Best': 4}, {'Gfg': 4, 'is': 4, 'Best': 5}, {'Gfg': 4, 'is': 5, 'Best': 4}, {'Gfg': 4, 'is': 5, 'Best': 5}, {'Gfg': 5, 'is': 4, 'Best': 4}, {'Gfg': 5, 'is': 4, 'Best': 5}, {'Gfg': 5, 'is': 5, 'Best': 4}, {'Gfg': 5, 'is': 5, 'Best': 5}]
Time Complexity: O(n*n)
Auxiliary Space: O(n)
Method #2 : Using permutations() + dictionary comprehension + list comprehension [ For unique elements ]
If we require values to be all unique, permutations() can be used inplace of product() to achieve this task.
Output:
The original list 1 is : ['Gfg', 'is', 'Best'] The original list 2 is : [4, 5, 6] The combinations dictionary : [{'Gfg': 4, 'is': 5, 'Best': 6}, {'Gfg': 4, 'is': 6, 'Best': 5}, {'Gfg': 5, 'is': 4, 'Best': 6}, {'Gfg': 5, 'is': 6, 'Best': 4}, {'Gfg': 6, 'is': 4, 'Best': 5}, {'Gfg': 6, 'is': 5, 'Best': 4}]
Time Complexity: O(n!) where n is the number of elements in the list “test_list”. permutations() + dictionary comprehension + list comprehension performs n! number of operations.
Auxiliary Space: O(n), extra space of size n is required