首页 > 代码库 > python字典顺序转字符串

python字典顺序转字符串

普通字典默认是无序的:

比如:

1 a = {b: 1, a: 2}
2 print a
3 print repr(a)

输出:

1 {a: 2, b: 1}
2 {a: 2, b: 1}

有序的字典需要用到OrderedDict:

1 from collections import OrderedDict
2 a = OrderedDict()
3 a[b] = 2
4 a[a] = 1
5 print a
6 print repr(a)

输出:

1 OrderedDict([(b, 2), (a, 1)])
2 OrderedDict([(b, 2), (a, 1)])

用json的dumps方法将有序字典转为字符串:

1 from collections import OrderedDict
2 from json import dumps
3 a = OrderedDict()
4 a[b] = 2
5 a[a] = 1
6 print a
7 print dumps(a)

输出:

1 OrderedDict([(b, 2), (a, 1)])
2 {"b": 2, "a": 1}

 

python字典顺序转字符串