Python實現(xiàn)字典轉(zhuǎn)字符串的五種方法
在Python中,可以使用以下幾種方法將字典轉(zhuǎn)換為字符串:
1、使用json模塊的dumps方法:
import json
my_dict = {"key1": "value1", "key2": "value2"}
# 方法1:使用json模塊的dumps方法
dict_str = json.dumps(my_dict)
print(dict_str)
2、使用str方法:
my_dict = {"key1": "value1", "key2": "value2"}
# 方法2:使用str方法
dict_str = str(my_dict)
print(dict_str)
3、使用循環(huán)和字符串拼接:
my_dict = {"key1": "value1", "key2": "value2"}
# 方法3:使用循環(huán)和字符串拼接
dict_str = "{"
for key, value in my_dict.items():
dict_str += "'" + key + "': '" + value + "', "
dict_str = dict_str.rstrip(", ") + "}"
print(dict_str)
4、使用字符串的format方法:
my_dict = {"key1": "value1", "key2": "value2"}
# 方法4:使用字符串的format方法
dict_str = "{{'{}': '{}', '{}': '{}'}}".format(*my_dict.items())
print(dict_str)
5、使用字符串的join方法:
my_dict = {"key1": "value1", "key2": "value2"}
# 方法5:使用字符串的join方法
dict_str = '{' + ', '.join("'{}': '{}'".format(key, value) for key, value in my_dict.items()) + '}'
print(dict_str)
注意:以上所有方法都會將字典轉(zhuǎn)換成字符串格式,但最終輸出的字符串可能有不同的格式。
Python 字符串轉(zhuǎn)字典
在工作中遇到一個小問題,需要將一個 python 的字符串轉(zhuǎn)為字典,比如字符串:
user_info = '{"name" : "john", "gender" : "male", "age": 28}'我們想把它轉(zhuǎn)為下面的字典:
user_dict = {"name" : "john", "gender" : "male", "age": 28}有以下幾種方法:
1、通過 json 來轉(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 進(jìn)行轉(zhuǎn)換存在一個潛在的問題。
由于 json 語法規(guī)定 數(shù)組或?qū)ο笾械淖址仨毷褂秒p引號,不能使用單引號 (官網(wǎng)上有一段描述是 “A string is a sequence of zero or more Unicode characters, wrapped in double quotes, using backslash escapes” ),因此下面的轉(zhuǎn)換是錯誤的:
>>> import json
>>> user_info = "{'name' : 'john', 'gender' : 'male', 'age': 28}"
# 由于字符串使用單引號,會導(dǎo)致運行出錯
>>> user_dict = json.loads(user_info)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
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、通過 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 進(jìn)行轉(zhuǎn)換就不存在上面使用 json 進(jìn)行轉(zhuǎn)換的問題。但是,使用 eval 卻存在安全性的問題,比如下面的例子:
# 讓用戶輸入 `user_info`
>>> user_info = raw_input('input user info: ')
# 輸入 {"name" : "john", "gender" : "male", "age": 28},沒問題
>>> user_dict = eval(user_info)
# 輸入 __import__('os').system('dir'),user_dict 會列出當(dāng)前的目錄文件!
# 再輸入一些刪除命令,則可以把整個目錄清空了!
>>> user_dict = eval(user_info)3、通過 literal_eval(好處是字符串的bool類型可能是True,Python不認(rè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'}使用 ast.literal_eval 進(jìn)行轉(zhuǎn)換既不存在使用 json 進(jìn)行轉(zhuǎn)換的問題,也不存在使用 eval 進(jìn)行轉(zhuǎn)換的 安全性問題,因此推薦使用 ast.literal_eval。
以上就是Python實現(xiàn)字典轉(zhuǎn)字符串的五種方法的詳細(xì)內(nèi)容,更多關(guān)于Python字典轉(zhuǎn)字符串的資料請關(guān)注腳本之家其它相關(guān)文章!
相關(guān)文章
Python中Scrapy+adbapi提高數(shù)據(jù)庫寫入效率實現(xiàn)
本文主要介紹了Python中Scrapy+adbapi提高數(shù)據(jù)庫寫入效率實現(xiàn),文中通過示例代碼介紹的非常詳細(xì),具有一定的參考價值,感興趣的小伙伴們可以參考一下2021-10-10
python selenium操作cookie的實現(xiàn)
這篇文章主要介紹了python selenium操作cookie的實現(xiàn),文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2020-03-03
python利用PyQt5設(shè)計鼠標(biāo)顯示形狀
不知道大家有沒有發(fā)現(xiàn),我們在網(wǎng)頁移動鼠標(biāo)時,不同的網(wǎng)頁會有不同的鼠標(biāo)移動特效,通過移動鼠標(biāo),會形成類似蜘蛛網(wǎng)等等的特效,本文將用PyQt5實現(xiàn)這一特效,需要的可以參考一下2024-07-07

