- 将str转化为dict
使用Python 3的内置ast库的函数literal_eval。最好使用literal_eval而不是eval
import ast
str_of_dict = "{'key1': 'key1value', 'key2': 'key2value'}"
ast.literal_eval(str_of_dict)
将输出作为实际的字典
{'key1': 'key1value', 'key2': 'key2value'}
- 将dict转化为str
my_dict = {'key1': 'key1value', 'key2': 'key2value'}
str(my_dict)
将打印:
"{'key1': 'key1value', 'key2': 'key2value'}"