Open In App

Python – Convert Key-Value list Dictionary to List of Lists

Last Updated : 24 Mar, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

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 + items() This brute force way in which we can perform this task. In this, we loop through all the pairs and extract list value elements using items() and render them in a new list. 

Python3




# Python3 code to demonstrate working of
# Convert Key-Value list Dictionary to Lists of List
# Using loop + items()
 
# initializing Dictionary
test_dict = {'gfg': [1, 3, 4], 'is': [7, 6], 'best': [4, 5]}
 
# printing original dictionary
print("The original dictionary is : " + str(test_dict))
 
# Convert Key-Value list Dictionary to Lists of List
# Using loop + items()
res = []
for key, val in test_dict.items():
    res.append([key] + val)
 
# printing result
print("The converted list is : " + str(res))


Output

The original dictionary is : {'gfg': [1, 3, 4], 'is': [7, 6], 'best': [4, 5]}
The converted list is : [['gfg', 1, 3, 4], ['is', 7, 6], ['best', 4, 5]]

Time complexity: O(n), where n is the number of items in the dictionary
Auxiliary space: O(n), as a new list “res” with n items is created.

Method #2: Using list comprehension This task can also be performed using list comprehension. In this, we perform the task similar to the above method just in a one-liner shorter way. 

Python3




# Python3 code to demonstrate working of
# Convert Key-Value list Dictionary to Lists of List
# Using list comprehension
 
# initializing Dictionary
test_dict = {'gfg': [1, 3, 4], 'is': [7, 6], 'best': [4, 5]}
 
# printing original dictionary
print("The original dictionary is : " + str(test_dict))
 
# Convert Key-Value list Dictionary to Lists of List
# Using list comprehension
res = [[key] + val for key, val in test_dict.items()]
 
# printing result
print("The converted list is : " + str(res))


Output

The original dictionary is : {'gfg': [1, 3, 4], 'is': [7, 6], 'best': [4, 5]}
The converted list is : [['gfg', 1, 3, 4], ['is', 7, 6], ['best', 4, 5]]

Time complexity: O(n), where n is the number of key-value pairs in the dictionary
Auxiliary space: O(n), where n is the number of key-value pairs in the dictionary. 

Method #3: Using map and dict.keys() This task can also be performed. In this, we get the keys value of dict and iterate over the list of keys and get the values of corresponding values and concatenate both key and value, and form a list of lists. 

Python




# Python3 code to demonstrate working of
# Convert Key-Value list Dictionary to Lists of List
# Using map + keys()
 
# initializing Dictionary
test_dict = {'gfg': [1, 3, 4], 'is': [7, 6], 'best': [4, 5]}
 
# printing original dictionary
print("The original dictionary is : " + str(test_dict))
 
temp1 = list(test_dict.keys())
# Convert Key-Value list Dictionary to Lists of List
# Using map + keys()
res = list(map(lambda i: [i] + test_dict[i], temp1))
 
# printing result
print("The converted list is : " + str(res))


Output

The original dictionary is : {'is': [7, 6], 'gfg': [1, 3, 4], 'best': [4, 5]}
The converted list is : [['is', 7, 6], ['gfg', 1, 3, 4], ['best', 4, 5]]

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

Method #4 : Using keys() and insert() method

Python3




# Python3 code to demonstrate working of
# Convert Key-Value list Dictionary to Lists of List
 
# initializing Dictionary
test_dict = {'gfg': [1, 3, 4], 'is': [7, 6], 'best': [4, 5]}
 
# printing original dictionary
print("The original dictionary is : " + str(test_dict))
 
# Convert Key-Value list Dictionary to Lists of List
res = []
for i in test_dict.keys():
    test_dict[i].insert(0, i)
    res.append(test_dict[i])
# printing result
print("The converted list is : " + str(res))


Output

The original dictionary is : {'gfg': [1, 3, 4], 'is': [7, 6], 'best': [4, 5]}
The converted list is : [['gfg', 1, 3, 4], ['is', 7, 6], ['best', 4, 5]]

Time complexity: O(n), where n is the number of keys in the dictionary. The for loop runs n times and the operations inside the loop take constant time.
Auxiliary Space: O(n), where n is the number of keys in the dictionary. The space required to store the output list ‘res’ is proportional to the number of keys in the dictionary. The size of the input dictionary is not taken into account as it is not relevant to the space required for the output list.

Method #5: Using zip() function and list comprehension

In this approach, we can use the zip() function to combine the keys and values of the dictionary. We then use a list comprehension to convert each combined key-value pair into a list and store them in a final list.

Python3




# Python3 code to demonstrate working of
# Convert Key-Value list Dictionary to Lists of List
# Using zip() + list comprehension
 
# initializing Dictionary
test_dict = {'gfg': [1, 3, 4], 'is': [7, 6], 'best': [4, 5]}
 
# printing original dictionary
print("The original dictionary is : " + str(test_dict))
 
# Convert Key-Value list Dictionary to Lists of List
# Using zip() + list comprehension
res = [ [key]+value for key, value in zip(test_dict.keys(), test_dict.values()) ]
 
# printing result
print("The converted list is : " + str(res))


Output

The original dictionary is : {'gfg': [1, 3, 4], 'is': [7, 6], 'best': [4, 5]}
The converted list is : [['gfg', 1, 3, 4], ['is', 7, 6], ['best', 4, 5]]

Time complexity: O(n), where n is the number of key-value pairs in the dictionary.
Auxiliary space: O(n), where n is the number of key-value pairs in the dictionary, to store the final list.

Method #6: Using a nested list comprehension

Use a nested list comprehension to iterate over the keys in the dictionary and append the corresponding key and value as a list to the result list.

Step-by-step approach:

  • Initialize a dictionary with key-value pairs, where each value is a list.
  • Create an empty list to store the converted list of lists.
  • Iterate over the key-value pairs in the dictionary using a loop, or a list comprehension.
  • For each key-value pair, create a new list that consists of the key followed by the list of values.
  • Append the new list to the list of lists.
  • Return the list of lists.

Below is the implementation of the above approach:

Python




# initializing Dictionary
test_dict = {'gfg': [1, 3, 4], 'is': [7, 6], 'best': [4, 5]}
 
# printing original dictionary
print("The original dictionary is : " + str(test_dict))
 
# Convert Key-Value list Dictionary to Lists of List
# Using a nested list comprehension
res = [[key] + test_dict[key] for key in test_dict]
 
# printing result
print("The converted list is : " + str(res))


Output

The original dictionary is : {'is': [7, 6], 'gfg': [1, 3, 4], 'best': [4, 5]}
The converted list is : [['is', 7, 6], ['gfg', 1, 3, 4], ['best', 4, 5]]

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

Method 7: Using the items() method of the dictionary along with a for loop. 

Step-by-step approach:

  1. Initialize an empty list res.
  2. Iterate over the items in the test_dict dictionary using a for loop.
  3. For each item, create a list that contains the key of the item followed by the value of the item.
  4. Append the list created in step 3 to the res list.
  5. Print the res list.

Below is the implementation of the above approach:

Python3




# initializing Dictionary
test_dict = {'gfg': [1, 3, 4], 'is': [7, 6], 'best': [4, 5]}
 
# printing original dictionary
print("The original dictionary is : " + str(test_dict))
 
# Convert Key-Value list Dictionary to Lists of List
# Using items() method and for loop
res = []
for key, value in test_dict.items():
    res.append([key] + value)
 
# printing result
print("The converted list is : " + str(res))


Output

The original dictionary is : {'gfg': [1, 3, 4], 'is': [7, 6], 'best': [4, 5]}
The converted list is : [['gfg', 1, 3, 4], ['is', 7, 6], ['best', 4, 5]]

Time complexity: O(n), where n is the number of key-value pairs in the test_dict dictionary.
Auxiliary space: O(n), where n is the number of key-value pairs in the test_dict dictionary (to store the res list).



Similar Reads

Python - Convert Lists into Similar key value lists
Given two lists, one of key and other values, convert it to dictionary with list values, if keys map to different values on basis of index, add in its value list. Input : test_list1 = [5, 6, 6, 6], test_list2 = [8, 3, 2, 9] Output : {5: [8], 6: [3, 2, 9]} Explanation : Elements with index 6 in corresponding list, are mapped to 6. Input : test_list1
12 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
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
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
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. Merge Key Value Lists into Dictionary Python Using zip
8 min read
Python - Dictionary Key Value lists combinations
Given a dictionary with values as a list, extract all the possible combinations, both cross keys and with values. Input : test_dict = {"Gfg" : [4, 5], "is" : [1, 2], "Best" : [9, 4]} Output : {0: [['Gfg', 4], ['is', 1], ['Best', 9]], 1: [['Gfg', 4], ['is', 1], ['Best', 4]], 2: [['Gfg', 4], ['is', 2], ['Best', 9]], 3: [['Gfg', 4], ['is', 2], ['Best'
9 min read
Python - Combine two dictionaries having key of the first dictionary and value of the second dictionary
Given two dictionaries. The task is to merge them in such a way that the resulting dictionary contains the key from the first dictionary and the value from the second dictionary. Examples: Input : test_dict1 = {"Gfg" : 20, "is" : 36, "best" : 100}, test_dict2 = {"Gfg2" : 26, "is2" : 20, "best2" : 70} Output : {'Gfg': 26, 'is': 20, 'best': 70} Expla
8 min read
Python | Convert list of tuples to dictionary value lists
One among the problem of interconversion of data types in python is conversion of list of tuples to dictionaries, in which the keys are 1st elements of tuple, which are uniquely identified as keys in dictionary and it's corresponding value as a list of the corresponding value of respective keys as tuple's second element. Let's discuss how to solve
9 min read
Python - Convert tuple list to dictionary with key from a given start value
Given a tuple list, the following article focuses on how to convert it to a dictionary, with keys starting from a specified start value. This start value is only to give a head start, next keys will increment the value of their previous keys. Input : test_list = [(4, 5), (1, 3), (9, 4), (8, 2), (10, 1)], start = 4 Output : {4: (4, 5), 5: (1, 3), 6:
4 min read
Practice Tags :