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

yipeiwu_com5年前Python基础

大致流程:

  • 导包---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文件:

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持【听图阁-专注于Python设计】。

相关文章

Python处理JSON时的值报错及编码报错的两则解决实录

1、ValueError: Invalid control character at: line 1 column 8363 (char 8362) 使用json.loads(json_...

浅谈django开发者模式中的autoreload是如何实现的

在开发django应用的过程中,使用开发者模式启动服务是特别方便的一件事,只需要 python manage.py runserver 就可以运行服务,并且提供了非常人性化的autore...

对于Python中RawString的理解介绍

总结 1、'''作用: 可以表示 "多行注释" 、"多行字符串" 、"其内的单双引号不转义" 2、r 代表的意思是: raw 3、r 只对其内的反斜杠起作用(注意单个 \ 的问题) ra...

介绍Python的Django框架中的静态资源管理器django-pipeline

 django-pipeline 是一个 Django 下非常方便的静态资源管理 app,尤其是 1.2 版本之后,利用 django-staticfiles 的collect...

numpy创建单位矩阵和对角矩阵的实例

在学习linear regression时经常处理的数据一般多是矩阵或者n维向量的数据形式,所以必须对矩阵有一定的认识基础。 numpy中创建单位矩阵借助identity()函数。更为准...