1. 程式人生 > >Python字符串轉為字典方法大全

Python字符串轉為字典方法大全

trac tin AD 因此 spa lose 方法大全 字符 cls

方法一: 通過內置函數eval

str_info = ‘{"name": "test", "age": 18}‘
dict_info = eval(str_info)

print("string info type is -->: %s" % (type(str_info)))
print("dict info type is -->: %s" % (type(dict_info)))
print(dict_info)

s_info = "{‘name‘: ‘nock‘, ‘age‘: 18}"
d_info = eval(s_info)

print("string info type is -->: %s" % (type(s_info)))
print("dict info type is -->: %s" % (type(d_info)))
print(d_info)

  

F:\python\python35\python.exe E:/code/clself/Test/test_example1.py
string info type is -->: <class ‘str‘>
dict info type is -->: <class ‘dict‘>
{‘name‘: ‘test‘, ‘age‘: 18}
string info type is -->: <class ‘str‘>
dict info type is -->: <class ‘dict‘>
{‘name‘: ‘nock‘, ‘age‘: 18}

Process finished with exit code 0

  

不過使用eval有一個安全性問題

方法二: 通過json模塊處理

import json
str_info = ‘{"name": "test", "age": 18}‘
dict_info = json.loads(str_info)

print("string info type is -->: %s" % (type(str_info)))
print("dict info type is -->: %s" % (type(dict_info)))
print(dict_info)

s_info = "{‘name‘: ‘nock‘, ‘age‘: 18}"
d_info = json.loads(s_info)

print("s info type is -->: %s" % (type(s_info)))
print("d info type is -->: %s" % (type(d_info)))
print(d_info)

結果如下:

F:\python\python35\python.exe E:/code/clself/Test/test_example1.py
string info type is -->: <class ‘str‘>
dict info type is -->: <class ‘dict‘>
{‘name‘: ‘test‘, ‘age‘: 18}
Traceback (most recent call last):
  File "E:/code/clself/Test/test_example1.py", line 10, in <module>
    d_info = json.loads(s_info)
  File "F:\python\python35\lib\json\__init__.py", line 319, in loads
    return _default_decoder.decode(s)
  File "F:\python\python35\lib\json\decoder.py", line 339, in decode
    obj, end = self.raw_decode(s, idx=_w(s, 0).end())
  File "F:\python\python35\lib\json\decoder.py", line 355, in raw_decode
    obj, end = self.scan_once(s, idx)
json.decoder.JSONDecodeError: Expecting property name enclosed in double quotes: line 1 column 2 (char 1)

Process finished with exit code 1

  

使用json模塊進行轉換存在一個問題,由於json語法規定 數組或對象之中的字符串必須使用雙引號,不能使用單引號

方法三: 通過ast模塊處理【推薦使用】

import ast
str_info = {"name": "test", "age": 18}
dict_info = ast.literal_eval(str_info)

print("string info type is -->: %s" % (type(str_info)))
print("dict info type is -->: %s" % (type(dict_info)))
print(dict_info)

s_info = "{‘name‘: ‘nock‘, ‘age‘: 18}"
d_info = ast.literal_eval(s_info)

print("s info type is -->: %s" % (type(s_info)))
print("d info type is -->: %s" % (type(d_info)))
print(d_info)
F:\python\python35\python.exe E:/code/clself/Test/test_example1.py
string info type is -->: <class ‘str‘>
dict info type is -->: <class ‘dict‘>
{‘name‘: ‘test‘, ‘age‘: 18}
s info type is -->: <class ‘str‘>
d info type is -->: <class ‘dict‘>
{‘name‘: ‘test‘, ‘age‘: 18}

使用ast.literal_eval進行轉換既不存在使用json 模塊進行轉換的問題,也不存在使用eval模塊進行轉換的安全性問題,因此推薦大家使用ast.literal_eval的方法。

Python字符串轉為字典方法大全