1.字符串转字典
#用eval转换
>>> s="{'name':'cxq','sex':'F'}"
>>> print(type(s))
<class 'str'>
>>> s=eval(s)
>>> print(s)
{'name': 'cxq', 'sex': 'F'}
>>> print(type(s))
<class 'dict'>
注:若用eval转换时,字段中有空字符串,就会报错,建议用json.loads转换
#用json.loads 转换
>>> s='{"name":"cxq","sex":"F"}'
>>> s=json.loads(s)
>>> s
{'name': 'cxq', 'sex': 'F'}
>>> print(type(s))
<class 'dict'>
注:此种方式转换时外层用单引号,内层用双引号
``
2.字典转字符串
#用json.dumps()
>>> s={"name":"cxq","sex":"F"}
>>> s=json.dumps(s)
>>> print(s)
{"name": "cxq", "sex": "F"}
>>> print(type(s))
<class 'str'>
#强制转换
>>> s={"name":"cxq","sex":"F"}
>>> s=str(s)
>>> s
"{'name': 'cxq', 'sex': 'F'}"
>>> print(type(s))
<class 'str'>