![]() |
VOOZH | about |
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().
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.
The 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:
Below is the implementation of the above approach:
Converted 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.