To convert a Python dictionary to a string and back, you can use the json module, which provides functions for serializing and deserializing data.
Converting a Dictionary to a String:
Use json.dumps() to serialize the dictionary into a JSON-formatted string:
import json
my_dict = {‘key1’: ‘value1’, ‘key2’: ‘value2’}
json_string = json.dumps(my_dict)
print(json_string) # Output: ‘{“key1”: “value1”, “key2”: “value2”}’
Converting a String Back to a Dictionary:
Use json.loads() to deserialize the JSON-formatted string back into a dictionary:
json_string = ‘{“key1”: “value1”, “key2”: “value2”}’
my_dict = json.loads(json_string)
print(my_dict) # Output: {‘key1’: ‘value1’, ‘key2’: ‘value2’}
This approach is recommended because it handles various data types and ensures that the data remains consistent.
Alternative Method Using ast.literal_eval():
If the string representation of the dictionary is simple and contains only literals, you can use ast.literal_eval() from the ast module:
import ast
dict_string = “{‘key1’: ‘value1’, ‘key2’: ‘value2’}”
my_dict = ast.literal_eval(dict_string)
print(my_dict) # Output: {‘key1’: ‘value1’, ‘key2’: ‘value2’}
However, this method is less flexible and may not handle all data types correctly.
For more details, refer to the Stack Overflow discussion on this topic.