python如何将字符串转换成字典dict类型

用eval()或exec()函数实现,本人习惯于用eval()

>>> user = "{'name' : 'jim', 'sex' : 'male', 'age': 18}"
>>> user['name']
Traceback (most recent call last):
  File "", line 1, in 
TypeError: string indices must be integers, not str
>>> b = eval(user)
>>> b
{'age': 18, 'name': 'jim', 'sex': 'male'}
>>> b['name']
'jim'
>>> exec("c="+user)
>>> c
{'age': 18, 'name': 'jim', 'sex': 'male'}
>>> c['age']
18
>>>

注意:这种方式要注意风险,因为eval实际上是解释执行python代码,如果输入来源于外部....,所以使用的使用要谨慎。

你可能感兴趣的:(python如何将字符串转换成字典dict类型)