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

猜你喜欢

转载自www.cnblogs.com/pythonRoad/p/11612022.html