本文实例讲述了python实现string和dict的相互转换方法。分享给大家供大家参考,具体如下:
字典(dict)转为字符串(string)
我们可以比较容易的将字典(dict)类型转为字符串(string)类型。
通过遍历dict中的所有元素就可以实现字典到字符串的转换:
?
1
2
for key, valuein sample_dic.items():
print "\"%s\":\"%s\"" % (key, value)
字符串(string)转为字典(dict)
如何将一个字符串(string)转为字典(dict)呢?
其实也很简单,只要用eval()或exec()函数就可以实现了。
?
1
2
3
4
5
6
7
8
>>> a= "{'a': 'hi', 'b': 'there'}"
>>> b= eval(a)
>>> b
{'a':'hi','b':'there'}
>>>exec ("c=" + a)
>>> c
{'a':'hi','b':'there'}
>>>
希望本文所述对大家Python程序设计有所帮助。