当前位置: 首页 > 图灵资讯 > 行业资讯> python如何将一串字符串转换为字典

python如何将一串字符串转换为字典

发布时间:2026-04-07 15:32:32

将字符串转换为字典的python方法:

1、通过 json 来转换

>>>importjson
>>>user_info='{"name":"john","gender":"male","age":28}'
>>>user_dict=json.loads(user_info)
>>>user_dict
{u'gender':u'male',u'age':28,u'name':u'john'}

由于json语法规定数组或对象中的字符串必须使用双引号,因此不能使用单引号(官方网站上的描述是 “A string is a sequence of zero or more Unicode characters, wrapped in double quotes, using backslash escapes” ),因此,以下转换是错误的:

>>>importjson
>>>user_info="{'name':'john','gender':'male','age':28}"
#由于字符串使用单引号,会导致操作错误
>>>user_dict=json.loads(user_info)
Traceback(mostrecentcalllast):
File"<stdin>",line1,in<module>
File"/usr/local/Cellar/python/2.7.11/Frameworks/Python.framework/Versions/2.7/lib/python2.7/json/__init__.py",line339,inloads
return_default_decoder.decode(s)
File"/usr/local/Cellar/python/2.7.11/Frameworks/Python.framework/Versions/2.7/lib/python2.7/json/decoder.py",line364,indecode
obj,end=self.raw_decode(s,idx=_w(s,0).end())
File"/usr/local/Cellar/python/2.7.11/Frameworks/Python.framework/Versions/2.7/lib/python2.7/json/decoder.py",line380,inraw_decode
obj,end=self.scan_once(s,idx)
ValueError:Expectingpropertyname:char1(line1column2)

2、通过 eval转换

>>>usr_info='{"name":"john","gender":"male","age":28}'
>>>user_dict=eval(user_info)
>>>user_dict
{'gender':'male','age':28,'name':'john'}
>>>user_info="{'name':'john','gender':'male','age':28}"
>>>user_dict=eval(user_info)
>>>user_dict
{'gender':'male','age':28,'name':'john'}

通过eval进行转换,不存在上述使用json进行转换的问题。但是,使用eval存在安全问题,如以下例子:

#让用户输入`user_info`
>>>user_info=raw_input('inputuserinfo:')
#输入{"name":"john","gender":"male","age":28},没问题
>>>user_dict=eval(user_info)
#输入__import__('os').system('dir'),user_dict将列出当前目录文件!
#输入一些删除命令,可以清空整个目录!
>>>user_dict=eval(user_info)

3、通过 literal_eval转换

>>>importast
>>>user='{"name":"john","gender":"male","age":28}'
>>>user_dict=ast.literal_eval(user)
>>>user_dict
{'gender':'male','age':28,'name':'john'}
user_info="{'name':'john','gender':'male','age':28}"
>>>user_dict=ast.literal_eval(user)
>>>user_dict
{'gender':'male','age':28,'name':'john'}

请关注Python视频教程栏目,了解更多Python知识。

相关文章

python如何将一串字符串转换为字典

python如何将一串字符串转换为字典

2026-04-07
python列表中去掉第几个值的方法

python列表中去掉第几个值的方法

2026-04-06
python列表怎么在指定元素前面添加元素

python列表怎么在指定元素前面添加元素

2026-04-06
python库怎么检查和安装?

python库怎么检查和安装?

2026-04-06
python集合可变吗?

python集合可变吗?

2026-04-06
怎么清除python编译器的语句

怎么清除python编译器的语句

2026-04-06