python将字典内容写⼊json⽂件的实例代码
python将字典内容写⼊json⽂件的⽅法:我们可以先使⽤json.dumps()函数将字典转换为字符串;然后再将内容写⼊json即可。json.dumps()函数负责对数据进⾏编码。
字典内容写⼊json时,需要⽤json.dumps将字典转换为字符串,然后再写⼊。
json也⽀持格式,通过参数indent可以设置缩进,如果不设置的话,则保存下来会是⼀⾏。
举例:
⽆缩进:
from collections import defaultdict, OrderedDict
import json
video = defaultdict(list)
video["label"].append("haha")
video["data"].append(234)
python怎么读取json文件
video["score"].append(0.3)
video["label"].append("xixi")
video["data"].append(123)
video["score"].append(0.7)
test_dict = {
'version': "1.0",
'results': video,
'explain': {
'used': True,
'details': "this is for josn test",
}
}
json_str = json.dumps(test_dict)
with open('test_data.json', 'w') as json_file:
json_file.write(json_str)
有缩进:
from collections import defaultdict, OrderedDict
import json
video = defaultdict(list)
video["label"].append("haha")
video["data"].append(234)
video["score"].append(0.3)
video["label"].append("xixi")
video["data"].append(123)
video["score"].append(0.7)
test_dict = {
'version': "1.0",
'results': video,
'explain': {
'used': True,
'details': "this is for josn test",
}
}
json_str = json.dumps(test_dict, indent=4)
with open('test_data.json', 'w') as json_file:
json_file.write(json_str)
以上就是python将字典内容写⼊json⽂件的实例代码的详细内容,更多关于python如何将字典内容写⼊json⽂件的资料请关注其它相关⽂章!

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。