Python Program to Convert dictionary string values to List of dictionaries
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
from collections import defaultdict
test_dict = { "Gfg" : "1:2:3:7:9" , "best" : "4:8" , "good" : "2" }
print ( "The original dictionary is : " + str (test_dict))
temp = defaultdict( dict )
for key in test_dict:
for idx in range ( len (test_dict[key].split( ':' ))):
try :
temp[idx][key] = test_dict[key].split( ':' )[idx]
except Exception as e:
temp[idx][key] = None
res = []
for key in temp:
res.append(temp[key])
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
Share your thoughts in the comments
Please Login to comment...