码迷,mamicode.com
首页 > 编程语言 > 详细

python-字典有序并写入json文件

时间:2019-09-30 12:23:37      阅读:133      评论:0      收藏:0      [点我收藏+]

标签:eal   dump   val   src   image   图片   json   png   com   

大致流程:

  1. 导包---import collections
  2. 新建一个有序字典---collections.OrderedDict()
  3. 写入json文件
代码:
 1 import collections
 2 real_result = collections.OrderedDict()
 3 real_result["target"] = "total_result"
 4 real_result["key1"] = "value1"
 5 real_result["key2"] = "value2"
 6 real_result["key3"] = "value3"
 7 real_result_total = [real_result]
 8 print real_result_total
 9 
10 输出:[OrderedDict([(‘target‘, ‘total_result‘), (‘key1‘, ‘value1‘), (‘key2‘, ‘value2‘), (‘key3‘, ‘value3‘)])]
11 
12 current_dir = os.path.dirname(os.path.realpath(__file__))
13 path = os.path.join(os.path.join(current_dir, ‘jsonfile‘), result_json)
14 with open(path, ‘w‘) as f:
15     json.dump(real_result_total, f, encoding="utf-8", ensure_ascii=False, indent=4, separators=(‘,‘, ‘:‘))

json文件:

技术图片

 

python-字典有序并写入json文件

标签:eal   dump   val   src   image   图片   json   png   com   

原文地址:https://www.cnblogs.com/pythonRoad/p/11612022.html

踩
(0)
赞
(0)
   
举报
评论 一句话评论(0)
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!