python3中字符串与字典的相互转换

一、字典(dict)转为字符串(string)

我们可以比较容易的将字典(dict)类型转为字符串(string)类型。

通过遍历dict中的所有元素就可以实现字典到字符串的转换:

for key, value in sample_dic.items():
  print ""%s":"%s"" % (key, value)

二、字符串(string)转为字典(dict)

如何将一个字符串(string)转为字典(dict)呢?

其实也很简单,只要用 eval()或exec() 函数就可以实现了。

>>> a = "{'a': 'hi', 'b': 'there'}"
>>> b = eval(a)
>>> b
{'a': 'hi', 'b': 'there'}
>>> exec ("c=" + a)
>>> c
{'a': 'hi', 'b': 'there'}
>>>
方法2:
引入json模块,使用loads方法
import json
str_dict ={"backend": "test.oldboy.org","record":{"server": "100.1.7.9999","weight": 20,"maxconn": 30}}#注意里面的字符必须是双引号
change_dict = json.loads(str_dict)
输出:{'record': {'server': '100.1.7.9999', 'weight': 20, 'maxconn': 30}, 'backend': 'test.oldboy.org'}
原文地址:https://www.cnblogs.com/jamchen/p/6423029.html