Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • Python Tutorial
  • Interview Questions
  • Python Quiz
  • Python Glossary
  • Python Projects
  • Practice Python
  • Data Science With Python
  • Python Web Dev
  • DSA with Python
  • Python OOPs
Open In App
Next Article:
Convert Dictionary String Values to List of Dictionaries - Python
Next article icon

Convert Dictionary Value list to Dictionary List Python

Last Updated : 24 Jun, 2023
Comments
Improve
Suggest changes
Like Article
Like
Report

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 = [{‘Gfg’: [5, 6]}, {‘best’: [3, 1]}] 
Output : [{‘Gfg’: 5, ‘best’: 3}, {‘Gfg’: 6, ‘best’: 1}]

Input : test_list = [{‘Gfg’: [5]}] 
Output : [{‘Gfg’: 5}] 

Convert Dictionary Value list to Dictionary Using loop 

This is one of the ways in which this problem can be solved. In this, we perform the task in brute force manner iterating each list value index and designating a key to it. 

Step-by-step approach:

  • Create an empty list res that will hold the converted dictionaries.
  • Initialize idx to 0. This variable will be used to track the index of the current dictionary in res.
  • Loop through each dictionary in test_list.
    • For each dictionary in test_list, loop through each key-value pair using the items() method.
      • For each value in the current key-value pair, loop through the elements of the list using a for loop.
      • For each element in the list, assign a new dictionary to res[idx] where the key is the current key and the value is the current element.
      • Increment the idx variable to move on to the next dictionary in res.
    • Reset idx to 0, since we only want one key-value pair in each dictionary in res.
  • Print the converted list using the print() function.

Below is the implementation of the above approach:

Python3




# Python3 code to demonstrate working of
# Convert Dictionary Value list to Dictionary List
# Using loop
 
# initializing list
test_list = [{'Gfg' : [5, 6, 5]}, {'is' : [10, 2, 3]}, {'best' : [4, 3, 1]}]
 
# printing original list
print("The original list is : " + str(test_list))
 
# Convert Dictionary Value list to Dictionary List
# Using loop
res =[{} for idx in range(len(test_list))]
idx = 0
for sub in test_list:
    for key, val in sub.items():
        for ele in val:
            res[idx][key] = ele
            idx += 1
        idx = 0
         
# printing result
print("Records after conversion : " + str(res))
 
 
Output
The original list is : [{'Gfg': [5, 6, 5]}, {'is': [10, 2, 3]}, {'best': [4, 3, 1]}] Records after conversion : [{'Gfg': 5, 'is': 10, 'best': 4}, {'Gfg': 6, 'is': 2, 'best': 3}, {'Gfg': 5, 'is': 3, 'best': 1}]

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

Convert Dictionary Value list to Dictionary Using list comprehension + zip() 

This is yet another way in which we can perform this task. In this, we perform task in 2 steps, first, we extract all the keys and then pair up values using zip() accordingly.

Python3




# Python3 code to demonstrate working of
# Convert Dictionary Value list to Dictionary List
# Using list comprehension + zip()
 
# initializing list
test_list = [{'Gfg' : [5, 6, 5]},
             {'is' : [10, 2, 3]},
             {'best' : [4, 3, 1]}]
 
# printing original list
print("The original list is : " + str(test_list))
 
# Convert Dictionary Value list to Dictionary List
# Using list comprehension + zip()
keys = [list(sub.keys())[0] for sub in test_list]
vals = zip(*[val for sub in test_list for val in sub.values()])
res = [dict(zip(keys, val)) for val in vals]
 
# printing result
print("Records after conversion : " + str(res))
 
 
Output
The original list is : [{'Gfg': [5, 6, 5]}, {'is': [10, 2, 3]}, {'best': [4, 3, 1]}] Records after conversion : [{'Gfg': 5, 'is': 10, 'best': 4}, {'Gfg': 6, 'is': 2, 'best': 3}, {'Gfg': 5, 'is': 3, 'b...

Time complexity: O(nm), where n is the length of the original list and m is the length of the value list in each dictionary.
Auxiliary space: O(nm).

Convert Dictionary Value list to Dictionary Using loop + enumerate()

Use a loop to iterate over the original list of dictionaries and extract the key-value pairs from each dictionary. It then assigns each value to the corresponding dictionary in the result list.

 step-by-step approach of the program:

  1. Initialize a list test_list with three dictionaries, where each dictionary has a single key-value pair.
  2. Print the original list using the print() function and string concatenation with str().
  3. Initialize a list res with empty dictionaries, where the number of dictionaries is equal to the length of test_list.
  4. Iterate over the test_list using a for loop with the enumerate() function. For each dictionary d in test_list:
    Get the key-value pair of the dictionary as a list of tuples using the items() method, then get the first tuple in the list using indexing [0].
    Assign the key to the variable key and the value to the variable val.
    Iterate over the values in val using another for loop with the enumerate() function. For each value v in val:
    Assign the value of v to the corresponding key in res using indexing.
  5. Print the result using the print() function and string concatenation with str().

Python3




# initializing list
test_list = [{'Gfg' : [5, 6, 5]}, {'is' : [10, 2, 3]}, {'best' : [4, 3, 1]}]
 
# printing original list
print("The original list is : " + str(test_list))
 
# Convert Dictionary Value list to Dictionary List
# Using loop
res = [{} for i in range(len(test_list))]
for i, d in enumerate(test_list):
    key, val = list(d.items())[0]
    for j, v in enumerate(val):
        res[j][key] = v
 
# printing result
print("Records after conversion : " + str(res))
 
 
Output
The original list is : [{'Gfg': [5, 6, 5]}, {'is': [10, 2, 3]}, {'best': [4, 3, 1]}] Records after conversion : [{'Gfg': 5, 'is': 10, 'best': 4}, {'Gfg': 6, 'is': 2, 'best': 3}, {'Gfg': 5, 'is': 3, 'best': 1}]

Time complexity: O(n*m), where n is the length of the original list and m is the length of the value list in each dictionary.
Auxiliary space: O(n*m).

Convert Dictionary Value list to Dictionary Using Dictionary comprehension + map()

The program achieves this using a dictionary comprehension and the built-in function map(). The map() function is used to extract the key-value pairs from each dictionary in the input list. The dictionary comprehension is used to create a new dictionary with the extracted key-value pairs. We iterate over the length of the value list in the first dictionary in the input list to ensure that we create a dictionary for each element in the value list.

Python3




# initializing list
test_list = [{'Gfg' : [5, 6, 5]},
             {'is' : [10, 2, 3]},
             {'best' : [4, 3, 1]}]
 
# printing original list
print("The original list is : " + str(test_list))
 
# Convert Dictionary Value list to Dictionary List
# Using dictionary comprehension and map()
res = [{k: v[i] for k, v in map(lambda x: (list(x.keys())[0],
                                           list(x.values())[0]),
                                test_list)} for i in range(len(list(test_list[0].values())[0]))]
 
# printing result
print("Records after conversion : " + str(res))
 
 
Output
The original list is : [{'Gfg': [5, 6, 5]}, {'is': [10, 2, 3]}, {'best': [4, 3, 1]}] Records after conversion : [{'Gfg': 5, 'is': 10, 'best': 4}, {'Gfg': 6, 'is': 2, 'best': 3}, {'Gfg': 5, 'is': 3, 'best': 1}]

Convert Dictionary Value list to Dictionary Using the defaultdict function 

Python3




from collections import defaultdict
 
# initializing list
test_list = [{'Gfg' : [5, 6, 5]}, {'is' : [10, 2, 3]}, {'best' : [4, 3, 1]}]
 
# printing original list
print("The original list is : " + str(test_list))
 
# Convert Dictionary Value list to Dictionary List using defaultdict
res = defaultdict(list)
for d in test_list:
    for key, val in d.items():
        res[key].extend(val)
 
# Convert the defaultdict to a list of dictionaries
res = [dict(zip(res.keys(), x)) for x in zip(*res.values())]
 
# printing result
print("Records after conversion : " + str(res))
 
 
Output
The original list is : [{'Gfg': [5, 6, 5]}, {'is': [10, 2, 3]}, {'best': [4, 3, 1]}] Records after conversion : [{'Gfg': 5, 'is': 10, 'best': 4}, {'Gfg': 6, 'is': 2, 'best': 3}, {'Gfg': 5, 'is': 3, 'best': 1}]

Time complexity: O(nm), where n is the length of the input list and m is the maximum length of the value lists in the input dictionaries. 
Auxiliary space: O(nm), as we are creating a defaultdict and a list of dictionaries.

Convert Dictionary Value list to Dictionary Using the Recursive method

  1. Define a function dict_val_to_list that takes test_list, idx (optional with default 0), and res (optional with default None) as arguments.
  2. If res is None, initialize res as a list of dictionaries with the same length as test_list.
  3. If idx is greater than or equal to the length of test_list, return res.
  4. Iterate over key-value pairs in the dictionary at index idx of test_list.
  5. Iterate over values in the current value list.
  6. Update the dictionary at the current index of res with the current key and value.
  7. Make a recursive call to dict_val_to_list with the next index of test_list and the updated res.
  8. Return res.

Python3




# Python program for the above approach
 
# Function to convert the dictionary
# value to list
def dict_val_to_list(test_list, idx=0, res=None):
   
    # initialize result list on first call
    if res is None:
        res = [{} for _ in range(len(test_list))]
 
    # base case: reached end of list
    # of dictionaries
    if idx >= len(test_list):
        return res
 
    # iterate over key-value pairs in
    # the current dictionary
    for key, val in test_list[idx].items():
       
        # iterate over values in the
        # current value list
        for i, ele in enumerate(val):
           
            # update the result dictionary
            # with current key and value
            res[i][key] = ele
 
        # recursive call to process next
        # dictionary in the list
        dict_val_to_list(test_list, idx+1, res)
 
    return res
 
# Driver Code
 
test_list = [{'Gfg': [5, 6, 5]}, {'is': [10, 2, 3]}, {'best': [4, 3, 1]}]
 
# Print the original list
print("The original list is : " + str(test_list))
 
res = dict_val_to_list(test_list)
 
# Print the result
print("Records after conversion : " + str(res))
 
 
Output
The original list is : [{'Gfg': [5, 6, 5]}, {'is': [10, 2, 3]}, {'best': [4, 3, 1]}] Records after conversion : [{'Gfg': 5, 'is': 10, 'best': 4}, {'Gfg': 6, 'is': 2, 'best': 3}, {'Gfg': 5, 'is': 3, 'best': 1}]

Time Complexity: O(N*M) where N is the length of test_list and M is the maximum length of the value lists in the dictionaries.
Space Complexity: O(N*M) for the output list of dictionaries.



Next Article
Convert Dictionary String Values to List of Dictionaries - Python
author
manjeet_04
Improve
Article Tags :
  • Python
  • Python Programs
  • Python list-programs
Practice Tags :
  • python

Similar Reads

  • Python - Convert list of dictionaries to Dictionary Value list
    We are given a list of dictionaries we need to convert it to dictionary. For example, given a list of dictionaries: d = [{'a': 1, 'b': 2}, {'a': 3, 'b': 4}, {'a': 5, 'b': 6}], the output should be: {'a': [1, 3, 5], 'b': [2, 4, 6]}. Using Dictionary ComprehensionUsing dictionary comprehension, we can
    3 min read
  • Convert List of Dictionaries to Dictionary of Lists - Python
    We are given a list of dictionaries we need to convert it to dictionaries of lists. For example, we are given a list of dictionaries li = [{'manoj': 'java', 'bobby': 'python'}, {'manoj': 'php', 'bobby': 'java'}, {'manoj': 'cloud', 'bobby': 'big-data'}] we need to convert this to dictionary of list s
    3 min read
  • Convert Dictionary String Values to List of Dictionaries - Python
    We are given a dictionary where the values are strings containing delimiter-separated values and the task is to split each string into separate values and convert them into a list of dictionaries, with each dictionary containing a key-value pair for each separated value. For example: consider this d
    2 min read
  • Python - Convert Key-Value list Dictionary to List of Lists
    We are given a key value list dictionary we need to convert it list of lists. For example we are given a dictionary a = {'name': 'Geeks', 'age': 8, 'city': 'Noida'} we need to convert this into list of lists so the output should be [['name', 'Geeks'], ['age', 25], ['city', 'Geeks']]. Using List Comp
    3 min read
  • Convert List to Single Dictionary Key - Value list - Python
    We are given a list and a element K, our aim is to transform the given list into a dictionary where the specified element (Kth element) becomes the key and the rest of the elements form the value list. For example: if the given list is: [6, 5, 3, 2] and K = 1 then the output will be {5: [6, 3, 2]}.
    4 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
    8 min read
  • Python Convert Dictionary to List of Values
    Python has different types of built-in data structures to manage your data. A list is a collection of ordered items, whereas a dictionary is a key-value pair data. Both of them are unique in their own way. In this article, the dictionary is converted into a list of values in Python using various con
    3 min read
  • Python - Convert key-values list to flat dictionary
    We are given a list that contains tuples with the pairs of key and values we need to convert that list into a flat dictionary. For example a = [("name", "Ak"), ("age", 25), ("city", "NYC")] is a list we need to convert it to dictionary so that output should be a flat dictionary {'name': 'Ak', 'age':
    3 min read
  • Python - Convert List to Index and Value dictionary
    Given a List, convert it to dictionary, with separate keys for index and values. Input : test_list = [3, 5, 7, 8, 2, 4, 9], idx, val = "1", "2" Output : {'1': [0, 1, 2, 3, 4, 5, 6], '2': [3, 5, 7, 8, 2, 4, 9]} Explanation : Index and values mapped at similar index in diff. keys., as "1" and "2". Inp
    3 min read
  • Convert Matrix to Dictionary Value List - Python
    We are given a matrix and the task is to map each column of a matrix to customized keys from a list. For example, given a matrix li = [[4, 5, 6], [1, 3, 5], [3, 8, 1], [10, 3, 5]] and a list map_li = [4, 5, 6], the goal is to map the first column to the key 4, the second column to the key 5, and the
    3 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences