本文以實(shí)例形式簡(jiǎn)述了Python中字符串類型與字典類型相互轉(zhuǎn)換的方法,是比較實(shí)用的功能。具體方法如下:
一、字典(dict)轉(zhuǎn)為字符串(string)
我們可以比較容易的將字典(dict)類型轉(zhuǎn)為字符串(string)類型。
通過(guò)遍歷dict中的所有元素就可以實(shí)現(xiàn)字典到字符串的轉(zhuǎn)換:
for key, value in sample_dic.items(): print "/"%s/":/"%s/"" % (key, value)
二、字符串(string)轉(zhuǎn)為字典(dict)
如何將一個(gè)字符串(string)轉(zhuǎn)為字典(dict)呢?
其實(shí)也很簡(jiǎn)單,只要用 eval()或exec() 函數(shù)就可以實(shí)現(xiàn)了。
>>> a = "{'a': 'hi', 'b': 'there'}">>> b = eval(a)>>> b{'a': 'hi', 'b': 'there'}>>> exec ("c=" + a)>>> c{'a': 'hi', 'b': 'there'}>>>感興趣的朋友可以調(diào)試運(yùn)行本實(shí)例,以加深對(duì)程序代碼的理解。
新聞熱點(diǎn)
疑難解答
圖片精選