Open In App

Python Program to Convert dictionary string values to List of dictionaries

Improve
Improve
Like Article
Like
Save
Share
Report

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.

Example:

Python3




# 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(':'))):
        try:
            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
    res.append(temp[key])
 
# printing result
print("Required dictionary list : " + str(res))


Output:

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)



Last Updated : 20 Feb, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads