首页 > 编程 > Python > 正文

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

2019-11-25 11:38:12
字体:
来源:转载
供稿:网友

大致流程:

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

代码:

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

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持武林网。

发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表