OrderedDict 有序的dict 并转化为json

之前认为字典是无序的,但是python中有个模块collections(英文,收集、集合),里面自带了一个子类OrderedDict,实现了对字典对象中元素的排序
例如:

print “无序dict”
d={}
d[‘a’]=‘A’
d[‘b’]=‘B’
d[‘c’]=‘C’

print “有序dict”
d1 = collections.OrderedDict()
d1[‘a’] = ‘A’
d1[‘b’] = ‘B’
d1[‘c’] = ‘C’
d1[‘1’] = ‘1’
d1[‘2’] = ‘2’

输出:
“无序dict”
a A
c C
b B

“有序dict”
a A
b B
c C
1 1
2 2

这个是重点
import json
from collections import OrderedDict
metadata = json.loads(text, object_pairs_hook=OrderedDict);

你可能感兴趣的:(后端常用命令)