Python字串轉為字典方法大全

2022-04-24 22:57:27 字數 2833 閱讀 3705

str_info = ''

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 = ""

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 -->: dict info type is -->:

string info type is -->: dict info type is -->:

process finished with exit code 0

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

import json

str_info = ''

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 = ""

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 -->: dict info type is -->:

traceback (most recent call last):

file "e:/code/clself/test/test_example1.py", line 10, in 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語法規定 陣列或物件之中的字串必須使用雙引號,不能使用單引號

import

aststr_info = '

'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 = "

"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 -->: dict info type is -->:

s info type is -->: d info type is -->:

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

Python 將字串轉為字典

在工作中遇到乙個小問題,需要將乙個python的字串轉為字典,比如字串 user info 我們想把它轉為下面的字典 user dict 有以下幾種方法 import json user info user dict json.loads user info user dict 但是使用json進行...

Python將字串轉為字典最佳實踐

在工作中我們經常會遇到資料型別之間的互轉的問題,而通常我們請求一些api藉口返回的結果就是字串,但是格式是json的,在python中轉為字典是最易處理的,所以這裡記錄一下在python下把字串轉為字典的三種方法。source code usr bin env python3 author nock...

Python 如何將字串轉為字典

在工作中遇到乙個小問題,需要將乙個python的字串轉為字典,比如字串 user info 我們想把它轉為下面的字典 user dict 有以下幾種方法 1 通過 json 來轉換 import json user info user dict json.loads user info user d...