python 字典有序并写入json文件过程解析

软件发布|下载排行|最新软件

当前位置:首页IT学院IT技术

python 字典有序并写入json文件过程解析

  2021-04-02 我要评论

大致流程:

  • 导包---import collections
  • 新建一个有序字典---collections.OrderedDict()
  • 写入json文件

代码:

import collections
real_result = collections.OrderedDict()
real_result["target"] = "total_result"
real_result["key1"] = "value1"
real_result["key2"] = "value2"
real_result["key3"] = "value3"
real_result_total = [real_result]
print real_result_total

输出:[OrderedDict([('target', 'total_result'), ('key1', 'value1'), ('key2', 'value2'), ('key3', 'value3')])]

current_dir = os.path.dirname(os.path.realpath(__file__))
path = os.path.join(os.path.join(current_dir, 'jsonfile'), result_json)
with open(path, 'w') as f:
  json.dump(real_result_total, f, encoding="utf-8", ensure_ascii=False, indent=4, separators=(',', ':'))

json文件:

您可能感兴趣的文章:

Copyright 2022 版权所有 软件发布 访问手机版

声明:所有软件和文章来自软件开发商或者作者 如有异议 请与本站联系 联系我们