如何在python 3. *中将字符串转换为字典? [英] how to convert string into dictionary in python 3.*?
本文介绍了如何在python 3. *中将字符串转换为字典?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想在不使用Python 3.5中的 eval()
函数的情况下将以下字符串转换为字典.
I want to convert the following string into dictionary without using eval()
function in Python 3.5.
d="{'Age': 7, 'Name': 'Manni'}";
有人能告诉我比使用 eval()
函数更好的方法吗?
Can anybody tell me the good way than using the eval()
function?
我真正想要的是一个可以直接将字典转换为字符串的函数.
What I really want is a function which can directly convert a dictionary to a string.
推荐答案
-
literal_eval
,一种稍微更安全的eval
版本(只会计算文字,例如字符串,列表等):
literal_eval
, a somewhat safer version ofeval
(will only evaluate literals ie strings, lists etc):
from ast import literal_eval
python_dict = literal_eval("{'a': 1}")
json.loads
,但这需要您的字符串使用双引号:
json.loads
but it would require your string to use double quotes:
import json
python_dict = json.loads('{"a": 1}')
这篇关于如何在python 3. *中将字符串转换为字典?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文