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


大致流程:

  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文件:

 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM