Python Program to Convert dictionary string values to List of dictionaries

Python Program to Convert dictionary string values to List of dictionaries

Let's say you have a dictionary with string values, and each string value can be interpreted as a dictionary. Our task will be to convert these string representations of dictionaries into actual dictionary objects and collect them as a list.

For this, the built-in module ast provides a function called literal_eval() which can safely evaluate a string containing a Python literal or container display.

Python Program:

Here's a Python program to convert string values in a dictionary to a list of dictionaries:

import ast def convert_string_values_to_dicts(input_dict): """Convert string representations of dictionaries in a dictionary to a list of dictionaries.""" return [ast.literal_eval(value) for value in input_dict.values()] # Testing the function sample_dict = { 'a': "{'name': 'John', 'age': 28}", 'b': "{'name': 'Doe', 'city': 'NY'}", 'c': "{'name': 'Smith', 'country': 'USA'}" } converted_list = convert_string_values_to_dicts(sample_dict) print(f"List of dictionaries: {converted_list}") 

Output:

List of dictionaries: [{'name': 'John', 'age': 28}, {'name': 'Doe', 'city': 'NY'}, {'name': 'Smith', 'country': 'USA'}] 

Explanation:

  • We imported the literal_eval() function from the ast module.

  • Inside the convert_string_values_to_dicts function, we use a list comprehension to iterate over each string value in the input dictionary.

  • For each string value, ast.literal_eval() safely evaluates the string and converts it into a dictionary.

  • The result is a list of dictionaries derived from the string values.

It's essential to ensure the string values in the input dictionary are valid dictionary representations, as literal_eval() will raise an error if it encounters invalid input.


More Tags

xcode-storyboard tfs auto-generate entities fragmenttransaction markers ssis-2012 game-physics guzzle kendo-listview

More Programming Guides

Other Guides

More Programming Examples