Python – Convert String to List of dictionaries

Given List of dictionaries in String format, Convert into actual List of Dictionaries.

Input : test_str = [“[{‘Gfg’ : 3, ‘Best’ : 8}, {‘Gfg’ : 4, ‘Best’ : 8}]”]
Output : [[{‘Gfg’: 3, ‘Best’: 8}, {‘Gfg’: 4, ‘Best’: 8}]]
Explanation : String converted to list of dictionaries.

Input : test_str = [“[{‘Gfg’ : 3, ‘Best’ : 8}]”]
Output : [[{‘Gfg’: 3, ‘Best’: 8}]]
Explanation : String converted to list of dictionaries.

Method #1 :  Using json.loads() + replace()

The combination of above functions can be used to solve this problem. In this, we replace the internal Strings using replace() and dictionary list is made using loads().



Python3

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python3 code to demonstrate working of 
# Convert String to List of dictionaries
# Using json.loads + replace()
import json
  
# initializing string
test_str = ["[{'Gfg' : 3, 'Best' : 8}, {'Gfg' : 4, 'Best' : 9}]"]
  
# printing original string
print("The original string is : " + str(test_str))
  
# replace() used to replace strings 
# loads() used to convert 
res = [json.loads(idx.replace("'", '"')) for idx in test_str]
      
# printing result 
print("Converted list of dictionaries : " + str(res)) 

chevron_right


Output

The original string is : ["[{'Gfg' : 3, 'Best' : 8}, {'Gfg' : 4, 'Best' : 9}]"]
Converted list of dictionaries : [[{'Gfg': 3, 'Best': 8}, {'Gfg': 4, 'Best': 9}]]

Method #2 : Using eval()

This is one of the ways in which this task can be performed. The eval(), internally evaluates the data type and returns required result.

Python3

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python3 code to demonstrate working of 
# Convert String to List of dictionaries
# Using json.loads + replace()
  
# initializing string
test_str = "[{'Gfg' : 3, 'Best' : 8}, {'Gfg' : 9, 'Best' : 9}]"
  
# printing original string
print("The original string is : " + str(test_str))
  
# eval() used to convert 
res = list(eval(test_str))
      
# printing result 
print("Converted list of dictionaries : " + str(res)) 

chevron_right


Output

The original string is : [{'Gfg' : 3, 'Best' : 8}, {'Gfg' : 9, 'Best' : 9}]
Converted list of dictionaries : [{'Gfg': 3, 'Best': 8}, {'Gfg': 9, 'Best': 9}]



My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.