用户工具

站点工具


python-hacks:string2dict

差别

这里会显示出您选择的修订版和当前版本之间的差别。

到此差别页面的链接

python-hacks:string2dict [2010/06/02 01:18] (当前版本)
行 1: 行 1:
 +====== Python中将字符串类型转为字典类型(string to dict) ======
 +
 +===== 字典(dict)转为字符串(string)=====
 + 
 +
 +我们可以比较容易的将字典(dict)类型转为字符串(string)类型。
 +
 +通过遍历dict中的所有元素就可以实现字典到字符串的转换:
 +
 +<code python>
 +for key, value in sample_dic.items():​
 +    print "​\"​%s\":​\"​%s\""​ % (key, value)
 +</​code>​
 +
 +===== 字符串(string)转为字典(dict)=====
 +
 +如何将一个字符串(string)转为字典(dict)呢?​
 +
 +其实也很简单,只要用 eval()或exec() 函数就可以实现了。
 +
 +<code python>
 +>>>​ a = "​{'​a':​ '​hi',​ '​b':​ '​there'​}"​
 +>>>​ b = eval(a)
 +>>>​ b
 +{'​a':​ '​hi',​ '​b':​ '​there'​}
 +>>>​ exec ("​c="​ + a)
 +>>>​ c
 +{'​a':​ '​hi',​ '​b':​ '​there'​}
 +>>>​
 +</​code>​
 +
  
python-hacks/string2dict.txt · 最后更改: 2010/06/02 01:18 (外部编辑)