這篇文章主要介紹python將一串字符串轉(zhuǎn)換為字典的方法,文中介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們一定要看完!
創(chuàng)新互聯(lián)主營(yíng)阿壩州網(wǎng)站建設(shè)的網(wǎng)絡(luò)公司,主營(yíng)網(wǎng)站建設(shè)方案,成都App定制開(kāi)發(fā),阿壩州h5小程序開(kāi)發(fā)搭建,阿壩州網(wǎng)站營(yíng)銷(xiāo)推廣歡迎阿壩州等地區(qū)企業(yè)咨詢
python中將字符串轉(zhuǎn)換為字典的方法:
1、通過(guò) json 來(lái)轉(zhuǎn)換
>>> import json >>> 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 語(yǔ)法規(guī)定 數(shù)組或?qū)ο笾械淖址仨毷褂秒p引號(hào),不能使用單引號(hào) (官網(wǎng)上有一段描述是 “A string is a sequence of zero or more Unicode characters, wrapped in double quotes, using backslash escapes” ),因此下面的轉(zhuǎn)換是錯(cuò)誤的:
>>> import json >>> user_info = "{'name' : 'john', 'gender' : 'male', 'age': 28}" # 由于字符串使用單引號(hào),會(huì)導(dǎo)致運(yùn)行出錯(cuò) >>> user_dict = json.loads(user_info) Traceback (most recent call last): File "", line 1, in File "/usr/local/Cellar/python/2.7.11/Frameworks/Python.framework/Versions/2.7/lib/python2.7/json/__init__.py", line 339, in loads 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", line 364, in decode 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", line 380, in raw_decode obj, end = self.scan_once(s, idx) ValueError: Expecting property name: line 1 column 2 (char 1)
2、通過(guò) eval轉(zhuǎn)換
>>> 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'}
通過(guò) eval 進(jìn)行轉(zhuǎn)換就不存在上面使用 json 進(jìn)行轉(zhuǎn)換的問(wèn)題。但是,使用 eval 卻存在安全性的問(wèn)題,比如下面的例子:
# 讓用戶輸入 `user_info` >>> user_info = raw_input('input user info: ') # 輸入 {"name" : "john", "gender" : "male", "age": 28},沒(méi)問(wèn)題 >>> user_dict = eval(user_info) # 輸入 __import__('os').system('dir'),user_dict 會(huì)列出當(dāng)前的目錄文件! # 再輸入一些刪除命令,則可以把整個(gè)目錄清空了! >>> user_dict = eval(user_info)
3、通過(guò) literal_eval轉(zhuǎn)換
>>> import ast >>> 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將一串字符串轉(zhuǎn)換為字典的方法的所有內(nèi)容,感謝各位的閱讀!希望分享的內(nèi)容對(duì)大家有幫助,更多相關(guān)知識(shí),歡迎關(guān)注創(chuàng)新互聯(lián)行業(yè)資訊頻道!