python- dictionary and write an orderly json file

General process:

  1. Guide package --- import collections
  2. Create an ordered dictionary --- collections.OrderedDict ()
  3. Write json file
Code:
 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 file:

 

Guess you like

Origin www.cnblogs.com/pythonRoad/p/11612022.html