Open In App

Python – Convert key-values list to flat dictionary

Last Updated : 27 Jul, 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 flatten dictionary of key-value pair pairing the equal index elements together. This can have utilities in web development and Data Science domain. Lets discuss certain way in which this task can be performed.

Convert key-values list to flat dictionary using zip() + dict()

The combination of above functions can be used to achieve the required task. In this, we perform the pairing using zip() and dict() is used to convert tuple data returned by zip() to dictionary format. 

Python3




# Python3 code to demonstrate working of
# Convert key-values list to flat dictionary
# Using dict() + zip()
from itertools import product
 
# initializing dictionary
test_dict = {'month' : [1, 2, 3],
             'name' : ['Jan', 'Feb', 'March']}
 
# printing original dictionary
print("The original dictionary is : " + str(test_dict))
 
# Convert key-values list to flat dictionary
# Using dict() + zip()
res = dict(zip(test_dict['month'], test_dict['name']))
 
# printing result
print("Flattened dictionary : " + str(res))


Output : 

The original dictionary is : {‘name’: [‘Jan’, ‘Feb’, ‘March’], ‘month’: [1, 2, 3]} Flattened dictionary : {1: ‘Jan’, 2: ‘Feb’, 3: ‘March’}

Time Complexity: O(n)
Auxiliary Space: O(n)

Convert key-values list to flat dictionary Using values() and dict() methods

Python3




# Python3 code to demonstrate working of
# Convert key-values list to flat dictionary
# initializing dictionary
test_dict = {'month' : [1, 2, 3],
            'name' : ['Jan', 'Feb', 'March']}
 
# printing original dictionary
print("The original dictionary is : " + str(test_dict))
 
# Convert key-values list to flat dictionary
x=list(test_dict.values())
a=x[0]
b=x[1]
d=dict()
for i in range(0,len(a)):
    d[a[i]]=b[i]
# printing result
print("Flattened dictionary : " + str(d))


Output

The original dictionary is : {'month': [1, 2, 3], 'name': ['Jan', 'Feb', 'March']}
Flattened dictionary : {1: 'Jan', 2: 'Feb', 3: 'March'}

The time complexity of this program is O(n), where n is the length of the longest list value in the dictionary. 

The auxiliary space complexity of this program is O(n), where n is the length of the longest list value in the dictionary. 

Convert key-values list to flat dictionary Using a dictionary comprehension

This method iterates over the indices of the ‘month’ list, and for each index i, it creates a key-value pair in the new dictionary where the key is the i-th element of the ‘month’ list, and the value is the i-th element of the ‘name’ list.

Python3




test_dict = {'month': [1, 2, 3], 'name': ['Jan', 'Feb', 'March']}
res = {test_dict['month'][i]: test_dict['name'][i] for i in range(len(test_dict['month']))}
print("Flattened dictionary:", res)


Output

Flattened dictionary: {1: 'Jan', 2: 'Feb', 3: 'March'}

Time complexity: O(N), where N is the length of the ‘month’ list.
Auxiliary space: O(N), since we are creating a new dictionary that has the same number of key-value pairs as the ‘month’ list.

Use a for loop to iterate over the keys and values and create a new dictionary by assigning each key-value pair to the new dictionary.

Step-by-step approach :

  • Initialize a dictionary test_dict with two keys ‘month’ and ‘name’, where the values are lists of integers and strings respectively.
  • Print the original dictionary using print() and str() functions.
  • Create an empty dictionary res to store the flattened key-value pairs.
  • Iterate over the range of the length of the ‘month’ list using a for loop.
  • For each iteration, use the current index i to access the i-th elements of the ‘month’ and ‘name’ lists using their respective keys in the test_dict dictionary.
  • Assign the key-value pair to the res dictionary using the key from the ‘month’ list and the corresponding value from the ‘name’ list.
  • Print the resulting flattened dictionary using print() and str() functions.

Below is the implementation of the above approach:

Python3




# Python3 code to demonstrate working of
# Convert key-values list to flat dictionary
# Using for loop
 
# initializing dictionary
test_dict = {'month' : [1, 2, 3],
             'name' : ['Jan', 'Feb', 'March']}
 
# printing original dictionary
print("The original dictionary is : " + str(test_dict))
 
# Convert key-values list to flat dictionary
# Using for loop
res = {}
for i in range(len(test_dict['month'])):
    res[test_dict['month'][i]] = test_dict['name'][i]
 
# printing result
print("Flattened dictionary : " + str(res))


Output

The original dictionary is : {'month': [1, 2, 3], 'name': ['Jan', 'Feb', 'March']}
Flattened dictionary : {1: 'Jan', 2: 'Feb', 3: 'March'}

Time complexity: O(n), where n is the number of key-value pairs in the dictionary. 
Auxiliary space: O(n), as we are creating a new dictionary to store the flattened key-value pairs.



Previous Article
Next Article

Similar Reads

Python - Convert Flat dictionaries to Nested dictionary
Sometimes, while working with records, we can have a problem in which we need to perform the task of conversion of multiple flat dictionaries to a single nested dictionary. This can have applications in many domains in which data is used extensively. Let's discuss certain ways by which we can convert flat dictionaries into nested dictionaries. Conv
4 min read
Python - Assigning Key values to list elements from Value list Dictionary
Given a List of elements, map them with keys of matching values from a value list. Input : test_list = [4, 6, 3, 5, 3], test_dict = {"Gfg" : [5, 3, 6], "is" : [8, 4]} Output : ['is', 'Gfg', 'Gfg', 'Gfg', 'Gfg'] Explanation : 4 is present in "is" key, hence mapped in new list. Input : test_list = [6, 3, 5, 3], test_dict = {"Gfg" : [5, 3, 6], "is" :
7 min read
Python - Convert Key-Value list Dictionary to List of Lists
Sometimes, while working with a Python dictionary, we can have a problem in which we need to perform the flattening of a key-value pair of dictionaries to a list and convert it to a list of lists. This can have applications in domains in which we have data. Let's discuss certain ways in which this task can be performed. Method #1: Using loop + item
8 min read
Python - Convert list to Single Dictionary Key Value list
Sometimes, while working with Python lists, we can have a problem in which we need to convert the list into a dictionary, which has single key, the Kth element of list, and others as its list value. This kind of problem can have applications in data domains. Let's discuss certain ways in which this task can be performed. Input : test_list = [6, 5,
7 min read
Python - Convert String List to Key-Value List dictionary
Given a string, convert it to key-value list dictionary, with key as 1st word and rest words as value list. Input : test_list = ["gfg is best for geeks", "CS is best subject"] Output : {'gfg': ['is', 'best', 'for', 'geeks'], 'CS': ['is', 'best', 'subject']} Explanation : 1st elements are paired with respective rest of words as list. Input : test_li
8 min read
Python - Extract Key's Value, if Key Present in List and Dictionary
Given a list, dictionary, and a Key K, print the value of K from the dictionary if the key is present in both, the list and the dictionary. Input : test_list = ["Gfg", "is", "Good", "for", "Geeks"], test_dict = {"Gfg" : 5, "Best" : 6}, K = "Gfg" Output : 5 Explanation : "Gfg" is present in list and has value 5 in dictionary. Input : test_list = ["G
11 min read
Convert Dictionary Value list to Dictionary List Python
Sometimes, while working with Python Dictionaries, we can have a problem in which we need to convert dictionary list to nested records dictionary taking each index of dictionary list value and flattening it. This kind of problem can have application in many domains. Let's discuss certain ways in which this task can be performed. Input : test_list =
9 min read
Python | Filter dictionary key based on the values in selective list
In Python, sometimes we require to get only some of the dictionary keys and not all. This problem is quite common in web development we require to get only the selective dictionary keys from some given list. Let's discuss certain ways in which this problem can be solved. Method #1: Using list comprehension The list comprehension can be used to solv
9 min read
Python - Sort Dictionary key and values List
Sometimes, while working with Python dictionaries, we can have a problem in which we need to perform the sorting of it, wrt keys, but also can have a variation in which we need to perform a sort on its values list as well. Let's discuss certain way in which this task can be performed. Input : test_dict = {'c': [3], 'b': [12, 10], 'a': [19, 4]} Outp
6 min read
Python program to update a dictionary with the values from a dictionary list
Given a dictionary and dictionary list, update the dictionary with dictionary list values. Input : test_dict = {"Gfg" : 2, "is" : 1, "Best" : 3}, dict_list = [{'for' : 3, 'all' : 7}, {'and' : 1, 'CS' : 9}] Output : {'Gfg': 2, 'is': 1, 'Best': 3, 'for': 3, 'all': 7, 'and': 1, 'CS': 9} Explanation : All dictionary keys updated in single dictionary. I
8 min read
Practice Tags :