Python - Convert String to List of dictionaries
Last Updated :
12 Apr, 2023
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
# 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))
OutputThe 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
# 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))
OutputThe original string is : [{'Gfg' : 3, 'Best' : 8}, {'Gfg' : 9, 'Best' : 9}]
Converted list of dictionaries : [{'Gfg': 3, 'Best': 8}, {'Gfg': 9, 'Best': 9}]
Time Complexity: O(n)
Auxiliary Space: O(n)
Method #4: Using regular expression and literal_eval()
Use regular expressions and the ast.literal_eval() function. This method involves using a regular expression to match all the dictionary literals in the input string and then passing each matched string to ast.literal_eval() to convert it to a dictionary object.
Step-by-step approach:
- Import the necessary modules, re and ast.
- Initialize a test string with a list of dictionaries.
- Define a regular expression pattern to match dictionary literals.
- Find all matches of dictionary literals in the input string using re.findall() method.
- Use ast.literal_eval() to convert each matched string to a dictionary object.
- Replace all single quotes with double quotes in each matched string before evaluating them using ast.literal_eval().
- Store the resulting dictionary objects in a list using list comprehension.
- Print the list of dictionaries.
Below is the implementation of the above approach:
Python3
import re
import ast
# initializing string
test_str = ["[{'Gfg' : 3, 'Best' : 8}, {'Gfg' : 4, 'Best' : 9}]"]
# define regular expression pattern to match dictionary literals
pattern = r"{[^{}]+}"
# find all matches of dictionary literals in input string
matches = re.findall(pattern, test_str[0])
# use ast.literal_eval() to convert each matched string to a dictionary object
res = [ast.literal_eval(match.replace("'", '"')) for match in matches]
# printing result
print("Converted list of dictionaries: ", res)
OutputConverted list of dictionaries: [{'Gfg': 3, 'Best': 8}, {'Gfg': 4, 'Best': 9}]
Time complexity: The regular expression matching operation takes O(n) time where n is the length of the input string.
Auxiliary space: O(m) auxiliary space to store each matched string temporarily in memory during the evaluation process.
Similar Reads
Convert Dictionary to String List in Python The task of converting a dictionary to a string list in Python involves transforming the key-value pairs of the dictionary into a formatted string and storing those strings in a list. For example, consider a dictionary d = {1: 'Mercedes', 2: 'Audi', 3: 'Porsche', 4: 'Lambo'}. Converting this to a st
3 min read
Convert List Of Dictionary into String - Python In Python, lists can contain multiple dictionaries, each holding key-value pairs. Sometimes, we need to convert a list of dictionaries into a single string. For example, given a list of dictionaries [{âaâ: 1, âbâ: 2}, {âcâ: 3, âdâ: 4}], we may want to convert it into a string that combines the conte
3 min read
Python - Convert List to List of dictionaries We are given a lists with key and value pair we need to convert the lists to List of dictionaries. For example we are given two list a=["name", "age", "city"] and b=[["Geeks", 25, "New York"], ["Geeks", 30, "Los Angeles"], ["Geeks", 22, "Chicago"]] we need to convert these keys and values list into
4 min read
Convert List of Lists to Dictionary - Python We are given list of lists we need to convert it to python . For example we are given a list of lists a = [["a", 1], ["b", 2], ["c", 3]] we need to convert the list in dictionary so that the output becomes {'a': 1, 'b': 2, 'c': 3}. Using Dictionary ComprehensionUsing dictionary comprehension, we ite
3 min read
Convert List of Dictionary to Tuple list Python Given a list of dictionaries, write a Python code to convert the list of dictionaries into a list of tuples.Examples: Input: [{'a':[1, 2, 3], 'b':[4, 5, 6]}, {'c':[7, 8, 9], 'd':[10, 11, 12]}] Output: [('b', 4, 5, 6), ('a', 1, 2, 3), ('d', 10, 11, 12), ('c', 7, 8, 9)] Below are various methods to co
5 min read