Open In App

Python – Value List Key Flattening

Last Updated : 10 May, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

Sometimes, while working with Python dictionaries, we can have a problem in which we need to perform pairing of each value of keys to extract the flattened dictionary. This kind of problem can have application in data domains. Lets discuss certain way in which this task can be performed.

Method #1: Using loop This is brute way in which this task can be performed. In this, we iterate for each of key’s values and assign it to its key and construct new key-value pair. 

Python3




# Python3 code to demonstrate working of
# Value List Key Flattening
# Using loop
 
# initializing dictionary
test_dict = {'gfg' : [4, 5, 7], 'best' : [10, 12]}
 
# printing original dictionary
print("The original dictionary : " + str(test_dict))
 
# Value List Key Flattening
# Using loop
res = []
for key, vals in test_dict.items():
    for ele in vals:
        res.append({"key": key, "value": ele})
 
# printing result
print("The flattened dictionary : " + str(res))


Output : 

The original dictionary : {'best': [10, 12], 'gfg': [4, 5, 7]}
The flattened dictionary : [{'value': 10, 'key': 'best'}, {'value': 12, 'key': 'best'}, {'value': 4, 'key': 'gfg'}, {'value': 5, 'key': 'gfg'}, {'value': 7, 'key': 'gfg'}]

Time Complexity: O(n*n), where n is the length of the list test_list 
Auxiliary Space: O(n) additional space of size n is created where n is the number of elements in the res list 

Method #2 : Using List Comprehension

we use list comprehension to iterate over the original dictionary and create a flattened list of dictionaries.

Step-by-step approach:

1. Create an empty list to store the flattened dictionary.
2. Iterate over the original dictionary using a for loop.
3. For each key in the dictionary, iterate over the corresponding list of values using another for loop.
4. Create a dictionary with keys “value” and “key” and append it to the flattened list.
5. Return the flattened list.

Python3




def flatten_dict(d):#define input
    flattened = [{'value': v, 'key': k} for k, v_list in d.items() for v in v_list]#get flattened dict
    return flattened#return result
d = {'best': [10, 12], 'gfg': [4, 5, 7]}#input
flattened_dict = flatten_dict(d)
print(flattened_dict)#print output


Output

[{'value': 10, 'key': 'best'}, {'value': 12, 'key': 'best'}, {'value': 4, 'key': 'gfg'}, {'value': 5, 'key': 'gfg'}, {'value': 7, 'key': 'gfg'}]

Time Complexity: O(nm), where n is the number of keys in the original dictionary and m is the maximum length of the value list for any key.
Space Complexity: O(nm), as we are creating a new dictionary for each value in the original dictionary.

Method #3: Using map() and lambda function:

Step-by-step approach:

1.Initialize an empty list called “flattened_dict”.
2.For each key-value pair in the input dictionary “d”, do the following:
a. For each value in the list associated with the key, create a dictionary with “value” and “key” keys and add it to the “flattened_dict” list.
3.Return the “flattened_dict” list.

Python3




from itertools import chain
 
d = {'best': [10, 12], 'gfg': [4, 5, 7]}
  
# printing original dictionary
print("The original dictionary : " + str(d))
  
 
flattened_dict = list(chain(*map(lambda k: [{'value': v, 'key': k} for v in d[k]], d.keys())))
 
print(flattened_dict)
#This code is contributed by Jyothi pinjala


Output

The original dictionary : {'best': [10, 12], 'gfg': [4, 5, 7]}
[{'value': 10, 'key': 'best'}, {'value': 12, 'key': 'best'}, {'value': 4, 'key': 'gfg'}, {'value': 5, 'key': 'gfg'}, {'value': 7, 'key': 'gfg'}]

Time Complexity: O(N*M), where N is the number of key-value pairs in the input dictionary and M is the maximum number of values associated with a key.
Space Complexity: O(N*M), where N is the number of key-value pairs in the input dictionary and M is the maximum number of values associated with a key.

Method #4: Using itertools.chain and dictionary comprehension

Step-by-step algorithm for the approach used to flatten the dictionary:

  1. Import the itertools module
  2. Initialize the original dictionary, test_dict
  3. Initialize an empty list for the flattened dictionary, flattened_dict
  4. Use list comprehension and itertools.chain to flatten the values of the original dictionary into a single iterable, flattened_values
  5. Use list comprehension and itertools.chain to repeat each key from the original dictionary len(v) times (where v is the value associated with the key), and flatten the resulting list of lists into a single list of keys, flattened_keys
  6. Use zip to pair up corresponding key-value pairs from the original dictionary, test_dict.items(), with the flattened values, flattened_values, and flattened keys, flattened_keys
  7. For each key-value pair, create a dictionary with the keys “key” and “value”, where “key” is the original dictionary key and “value” is the
  8. corresponding value from flattened_values, and append the dictionary to the flattened_dict list
  9. Print the flattened_dict list

Python3




# Import the itertools module
import itertools
 
# Initialize the original dictionary
test_dict = {'gfg' : [4, 5, 7], 'best' : [10, 12]}
 
# Initialize an empty list for the flattened dictionary
flattened_dict = []
 
# Use itertools and list comprehension to create a flattened dictionary
# The zip function pairs up corresponding key-value pairs from the original dictionary
# The itertools.chain function flattens the original dictionary values into a single iterable
# The list comprehension creates a dictionary for each key-value pair and appends it to the flattened_dict list
for k, v in zip(itertools.chain(*[[k]*len(v) for k, v in test_dict.items()]), itertools.chain(*test_dict.values())):
    flattened_dict.append({"key": k, "value": v})
 
# Print the flattened dictionary
print(flattened_dict)


Output

[{'key': 'gfg', 'value': 4}, {'key': 'gfg', 'value': 5}, {'key': 'gfg', 'value': 7}, {'key': 'best', 'value': 10}, {'key': 'best', 'value': 12}]

Time complexity: O(n), where n is the total number of values in the original dictionary.
Auxiliary space: O(n), where n is the total number of values in the original dictionary.

Method 5: Use the reduce function from the functools module

  1. Initialize an original dictionary named test_dict with two keys, ‘gfg’ and ‘best’, and their respective values.
  2. Use the reduce function from the functools module to combine all the values in the test_dict dictionary into a single list. The reduce function takes two arguments: a function to apply to the list elements and the list to apply the function to. In this case, we use a lambda function that simply concatenates two lists, and pass the values from test_dict as the list to apply the function to.
  3. Use a list comprehension to create a new list of key-value pairs for each element in the combined list. The zip function pairs up each value with its corresponding key, which we generate using a nested generator expression. The outer generator expression iterates over the keys in test_dict, while the inner generator expression creates a new instance of the current key for each element in the corresponding value list. The resulting list comprehension creates a new dictionary for each key-value pair with keys ‘key’ and ‘value’, and appends it to a new list called flattened_dict.
  4. Print the resulting flattened_dict list, which contains all the key-value pairs from the original dictionary flattened 

Python3




from functools import reduce
 
# Initialize the original dictionary
test_dict = {'gfg' : [4, 5, 7], 'best' : [10, 12]}
 
# Use reduce to combine all key-value pairs into a single list
combined = reduce(lambda x, y: x+y, test_dict.values())
 
# Use a list comprehension to create a new list of key-value pairs
flattened_dict = [{"key": k, "value": v} for k, v in zip((key for key in test_dict for _ in range(len(test_dict[key]))), combined)]
 
# Print the flattened dictionary
print(flattened_dict)


Output

[{'key': 'gfg', 'value': 4}, {'key': 'gfg', 'value': 5}, {'key': 'gfg', 'value': 7}, {'key': 'best', 'value': 10}, {'key': 'best', 'value': 12}]

Time complexity: O(n), where n is the total number of elements in the original dictionary. 
Auxiliary space: O(n), since the combined list holds all the values from the original dictionary.



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads