Open In App
Related Articles

Python Program to Convert dictionary string values to List of dictionaries

Improve Article
Save Article
Like Article

Given a dictionary with values as delimiter separated values, the task is to write a python program to convert each string as different value in list of dictionaries.

Input : test_dict = {“Gfg” : “1:2:3”, “best” : “4:8:11”} 
Output : [{‘Gfg’: ‘1’, ‘best’: ‘4’}, {‘Gfg’: ‘2’, ‘best’: ‘8’}, {‘Gfg’: ‘3’, ‘best’: ’11’}] 
Explanation : List after dictionary values split.

Input : test_dict = {“Gfg” : “1:2:3”} 
Output : [{‘Gfg’: ‘1’}, {‘Gfg’: ‘2”}, {‘Gfg’: ‘3’}] 
Explanation : List after dictionary values split. 

Method : Using loop and split()

The combination of above functions can be used to solve this problem. In this, we perform splitting of values of each key’s value and render it as separate value in a list of dictionaries.



# Python3 code to demonstrate working of
# Convert dictionary string values to Dictionaries List
# Using loop
from collections import defaultdict
# initializing dictionary
test_dict = {"Gfg": "1:2:3:7:9", "best": "4:8", "good": "2"}
# printing original dictionary
print("The original dictionary is : " + str(test_dict))
# create empty mesh
temp = defaultdict(dict)
for key in test_dict:
    # iterate for each of splitted values
    for idx in range(len(test_dict[key].split(':'))):
            temp[idx][key] = test_dict[key].split(':')[idx]
        # handle case with No value in split
        except Exception as e:
            temp[idx][key] = None
res = []
for key in temp:
    # converting nested dictionaries to list of dictionaries
# printing result
print("Required dictionary list : " + str(res))


The original dictionary is : {‘Gfg’: ‘1:2:3:7:9’, ‘best’: ‘4:8’, ‘good’: ‘2’}

Required dictionary list : [{‘Gfg’: ‘1’, ‘best’: ‘4’, ‘good’: ‘2’}, {‘Gfg’: ‘2’, ‘best’: ‘8’}, {‘Gfg’: ‘3’}, {‘Gfg’: ‘7’}, {‘Gfg’: ‘9’}]

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

Whether you're preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape, GeeksforGeeks Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we've already empowered, and we're here to do the same for you. Don't miss out - check it out now!

Last Updated : 20 Feb, 2023
Like Article
Save Article
Similar Reads
Complete Tutorials