一、字符串str转为字典dict
x = '{"a":1, "b":2}'
y = eval(x)
print(x, type(x))
print(y, type(y))
输出:
{"a":1, "b":2} <class 'str'> {'a': 1, 'b': 2} <class 'dict'>
二、字典dict转为字符串str
x = {"a":1, "b":2}
y = str(x)
print(x, type(x))
print(y, type(y))
输出:
{'a': 1, 'b': 2} <class 'dict'> {'a': 1, 'b': 2} <class 'str'>
三、字典dict与json数据互转
在Python中自带json库(import json导入)
在json模块有2个方法
import json
v = {"account": "clark", "password": "123456", "userType": 0}
json_str = json.dumps(v)
import json
data = json.loads(json_str)
注意区别:
import json
with open('d:/json.txt', 'r') as f:
x = json.load(f)
- dump():将dict数据转成json后写入json文件
import json
v = {"account": "clark", "password": "123456", "userType": 0}
with open('d:/json.txt', 'w') as f:
json.dump(v, f)
|