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)
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