Python – Key Value list pairings in Dictionary
Last Updated : 01 Jun, 2023
Sometimes, while working with Python dictionaries, we can have problems in which we need to pair all the keys with all values to form a dictionary with all possible pairings. This can have application in many domains including day-day programming. Lets discuss certain ways in which this task can be performed.
Method #1: Using list comprehension This task can be performed using this method. In this we manually extract each key and then iterate with all the values of them to form new dictionary list. This has drawbacks of only available for certain keys.
Python3
test_dict = { 'gfg' : [ 7 , 8 ], 'best' : [ 10 , 11 , 7 ]} print ( "The original dictionary is : " + str (test_dict)) res = [{ 'gfg' : i, 'best' : j} for i in test_dict[ 'gfg' ] for j in test_dict[ 'best' ]] print ( "All key value paired List : " + str (res)) |
Output : The original dictionary is : {‘gfg’: [7, 8], ‘best’: [10, 11, 7]} All key value paired List : [{‘gfg’: 7, ‘best’: 10}, {‘gfg’: 7, ‘best’: 11}, {‘gfg’: 7, ‘best’: 7}, {‘gfg’: 8, ‘best’: 10}, {‘gfg’: 8, ‘best’: 11}, {‘gfg’: 8, ‘best’: 7}]
The time complexity of the given code is O(N^2), where N is the size of the largest list in the dictionary.
The auxiliary space complexity of the given code is also O(N^2), as the result list ‘res’ contains N^2 key-value pairs, where N is the size of the largest list in the dictionary.
Method #2: Using dict() + zip() + product() The combination of above methods can also be used to perform this task. In this, the formation of combinations is done using product(), and linking of values is done using zip().
Python3
from itertools import product test_dict = { 'gfg' : [ 7 , 8 ], 'best' : [ 10 , 11 , 7 ]} print ( "The original dictionary is : " + str (test_dict)) res = [ dict ( zip (test_dict, sub)) for sub in product( * test_dict.values())] print ( "All key value paired List : " + str (res)) |
Output : The original dictionary is : {‘gfg’: [7, 8], ‘best’: [10, 11, 7]} All key value paired List : [{‘gfg’: 7, ‘best’: 10}, {‘gfg’: 7, ‘best’: 11}, {‘gfg’: 7, ‘best’: 7}, {‘gfg’: 8, ‘best’: 10}, {‘gfg’: 8, ‘best’: 11}, {‘gfg’: 8, ‘best’: 7}]
Time Complexity: O(n*n), where n is the length of the list test_dict
Auxiliary Space: O(n) additional space of size n is created where n is the number of elements in the res list
Method 3: Using a recursive approach
Step-by-step approach:
- Define a function called key_value_combinations that takes two arguments: keys and values. The keys argument is a list of keys, and the values argument is a list of lists, where each inner list represents the possible values for a key.
- In the function, create an empty list called combinations.
- Define a recursive function called generate_combinations that takes two arguments: current_combination and remaining_values. The current_combination argument is a dictionary that represents the key-value pairs generated so far, and the remaining_values argument is a list of lists, where each inner list represents the possible values for a key that has not been assigned a value yet.
- In the generate_combinations function, if the remaining_values list is empty, append the current_combination dictionary to the combinations list and return.
- Otherwise, pop the first list from the remaining_values list, and iterate over its elements. For each element, create a new dictionary by adding a key-value pair to the current_combination dictionary, where the key is the first key from the keys list, and the value is the current element from the popped list. Call the generate_combinations function recursively with the updated current_combination dictionary and the remaining values in the remaining_values list.
- Call the generate_combinations function with an empty dictionary as the current_combination argument and the values list as the remaining_values argument.
- Return the combinations list.
Below is the implementation of the above approach:
Python3
def key_value_combinations(keys, values): def generate_combinations(current_combination, remaining_values): if not remaining_values: combinations.append(current_combination) return values_list = remaining_values[ 0 ] remaining_values = remaining_values[ 1 :] for value in values_list: new_combination = current_combination.copy() new_combination[keys[ 0 ]] = value generate_combinations(new_combination, remaining_values) combinations = [] generate_combinations({}, values) return combinations test_dict = { 'gfg' : [ 7 , 8 ], 'best' : [ 10 , 11 , 7 ]} combinations = key_value_combinations( list (test_dict.keys()), list (test_dict.values())) print ( "All key value paired List : " + str (combinations)) |
Output All key value paired List : [{'gfg': 10}, {'gfg': 11}, {'gfg': 7}, {'gfg': 10}, {'gfg': 11}, {'gfg': 7}]
Time complexity: O(n^m), where n is the maximum length of any value list, and m is the number of keys.
Auxiliary space: O(n^m), as we need to store all possible combinations.
Method 4: Using itertools.product() with dictionary items()
Use the itertools.product() function along with the dictionary items() method to generate all possible combinations of key-value pairs.
Step-by-step approach:
- Get the items in the dictionary using the items() method and store them in a list.
- Use itertools.product() function to generate all possible combinations of values.
- Combine each combination with the corresponding keys using the zip() function and store them in a list.
Below is the implementation of the above approach:
Python3
import itertools def key_value_combinations(keys, values): items = list ( zip (keys, values)) value_combinations = itertools.product( * [item[ 1 ] for item in items]) combinations = [{items[i][ 0 ]: combination[i] for i in range ( len (items))} for combination in value_combinations] return combinations test_dict = { 'gfg' : [ 7 , 8 ], 'best' : [ 10 , 11 , 7 ]} combinations = key_value_combinations( list (test_dict.keys()), list (test_dict.values())) print ( "All key value paired List : " + str (combinations)) |
Output All key value paired List : [{'gfg': 7, 'best': 10}, {'gfg': 7, 'best': 11}, {'gfg': 7, 'best': 7}, {'gfg': 8, 'best': 10}, {'gfg': 8, 'best': 11}, {'gfg': 8, 'best': 7}]
Time complexity: O(n^m), where n is the maximum number of values for a key, and m is the number of keys.
Auxiliary space: O(n^m), to store all the combinations.
Method 5: Using nested for loops and a temporary dictionary
Step-by-step approach:
Define the dictionary test_dict with the given key-value pairs.
Print the original dictionary using print().
Initialize an empty list res to store the final result.
Use nested for loops to iterate over the values of the keys ‘gfg’ and ‘best’ in the dictionary test_dict.
For each pair of values, create a temporary dictionary temp_dict with the key-value pairs.
Append the temporary dictionary to the list res.
Print the final result using print().
Python3
test_dict = { 'gfg' : [ 7 , 8 ], 'best' : [ 10 , 11 , 7 ]} print ( "The original dictionary is : " + str (test_dict)) res = [] for i in test_dict[ 'gfg' ]: for j in test_dict[ 'best' ]: temp_dict = {} temp_dict[ 'gfg' ] = i temp_dict[ 'best' ] = j res.append(temp_dict) print ( "All key value paired List : " + str (res)) |
Output The original dictionary is : {'gfg': [7, 8], 'best': [10, 11, 7]} All key value paired List : [{'gfg': 7, 'best': 10}, {'gfg': 7, 'best': 11}, {'gfg': 7, 'best': 7}, {'gfg': 8, 'best': 10}, {'gfg': 8, 'best': 11}, {'gfg': 8, 'best': 7}]
Time complexity: O(n^2), where n is the length of the longest list in the dictionary test_dict.
Auxiliary space: O(1), because the algorithm only uses a temporary dictionary and a list to store the final result, regardless of the size of the input.
Similar Reads
Merge Key Value Lists into Dictionary Python
Sometimes, while working with lists, we can come forward with a problem in which we need to perform the merge function in which we have the key list and need to create dictionary mapping keys with corresponding value in other list. Let's discuss certain ways in which this task can be performed. Merg
8 min read
Python | List value merge in dictionary
Sometimes, while working with dictionaries, we can have a problem in which we have many dictionaries and we are required to merge like keys. This problem seems common, but complex is if the values of keys are list and we need to add elements to list of like keys. Let's discuss way in which this prob
5 min read
Python - Minimum value pairing for dictionary keys
Given two lists, key and value, construct a dictionary, which chooses minimum values in case of similar key value pairing. Input : test_list1 = [4, 7, 4, 8], test_list2 = [5, 7, 2, 9] Output : {8: 9, 7: 7, 4: 2} Explanation : For 4, there are 2 options, 5 and 2, 2 being smallest is paired. Input : t
7 min read
Python Print Dictionary Keys and Values
When working with dictionaries, it's essential to be able to print their keys and values for better understanding and debugging. In this article, we'll explore different methods to Print Dictionary Keys and Values. Example: Using print() Method [GFGTABS] Python my_dict = {'a': 1, 'b'
2 min read
Add a key value pair to Dictionary in Python
The task of adding a key-value pair to a dictionary in Python involves inserting new pairs or updating existing ones. This operation allows us to expand the dictionary by adding new entries or modify the value of an existing key. For example, starting with dictionary d = {'key1': 'geeks', 'key2': 'f
3 min read
Python - Print dictionary of list values
In this article, we will explore various ways on How to Print Dictionary in Python of list values. A dictionary of list values means a dictionary contains values as a list of dictionaries in Python. Example: {'key1': [{'key1': value,......,'key n': value}........{'key1': value,......,'key n': value}
4 min read
Inverse Dictionary Values List - Python
We are given a dictionary and the task is to create a new dictionary where each element of the value lists becomes a key and the original keys are grouped as lists of values for these new keys.For example: dict = {1: [2, 3], 2: [3], 3: [1]} then output will be {2: [1], 3: [1, 2], 1: [3]} Using defau
2 min read
Python - Mapping Key Values to Dictionary
We are given two list and we need to map key to values of another list so that it becomes dictionary. For example, we are given two list k = ['a', 'b', 'c'] and v = [1, 2, 3] we need to map the keys of list k to the values of list v so that the resultant output should be {'a': 1, 'b': 2, 'c': 3}. Us
3 min read
How to Print Dictionary Keys in Python
We are given a dictionary and our task is to print its keys, this can be helpful when we want to access or display only the key part of each key-value pair. For example, if we have a dictionary like this: {'gfg': 1, 'is': 2, 'best': 3} then the output will be ['gfg', 'is', 'best']. Below, are the me
2 min read
Get First N Key:Value Pairs in given Dictionary - Python
We are given a dictionary and tasked with retrieving the first N key-value pairs. For example, if we have a dictionary like this: {'a': 1, 'b': 2, 'c': 3, 'd': 4} and we need the first 2 key-value pairs then the output will be: {'a': 1, 'b': 2}. Using itertools.islice()One of the most efficient ways
3 min read