Skip to content
Related Articles

Related Articles

Improve Article

Python Program to Convert dictionary string values to List of dictionaries

  • Last Updated : 29 Jun, 2021

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.

 Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.  

To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course. And to begin with your Machine Learning Journey, join the Machine Learning - Basic Level Course

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’}]

My Personal Notes arrow_drop_up
Recommended Articles
Page :