Skip to content
Related Articles
Open in App
Not now

Related Articles

Python – Value List Key Flattening

Improve Article
Save Article
  • Last Updated : 16 Mar, 2023
Improve Article
Save Article

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'}]

Method #2 : Using List Comprehension

Approach

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

Algorithm

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:

Algorithm:

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 analysis:

The itertools.chain function and the list comprehension used to flatten the original dictionary values into a single iterable both have a time complexity of O(n), where n is the total number of values in the original dictionary.
The list comprehension used to repeat each key from the original dictionary and flatten the resulting list has a time complexity of O(n), where n is the total number of values in the original dictionary.
The zip function has a time complexity of O(n), where n is the total number of key-value pairs in the original dictionary.
The for loop that creates the flattened dictionary has a time complexity of O(n), where n is the total number of key-value pairs in the original dictionary.
Overall, the time complexity of the algorithm is O(n), where n is the total number of values in the original dictionary.
Auxiliary space analysis:

The itertools.chain function and the list comprehension used to flatten the original dictionary values into a single iterable both have an auxiliary space complexity of O(n), where n is the total number of values in the original dictionary.
The list comprehension used to repeat each key from the original dictionary and flatten the resulting list has an auxiliary space complexity of O(n), where n is the total number of values in the original dictionary.
The zip function has an auxiliary space complexity of O(n), where n is the total number of key-value pairs in the original dictionary.
The flattened_dict list has an auxiliary space complexity of O(n), where n is the total number of values in the original dictionary (since each key-value pair in the original dictionary will result in a dictionary with two keys in the flattened dictionary).
Overall, the auxiliary space complexity of the algorithm is O(n), where n is the total number of values in the original dictionary.


My Personal Notes arrow_drop_up
Related Articles

Start Your Coding Journey Now!