我有一个类似的列表
allsites = [
{
'A5': 'G',
'A10': 'G',
'site': 'example1.com',
'A1': 'G'
},
{
'A5': 'R',
'A10': 'Y',
'site': 'example2.com',
'A1': 'G'
}
]
我在 json.dumps
中使用:
data = { 'Author':"joe", 'data':allsites }
print json.dumps(data,sort_keys=True,indent=4, separators=(',', ': '))
这会输出以下 JSON:
{
"Author": "joe",
"data": [
{
"A1": "G",
"A10": "G",
"A5": "G",
"site": "example1.com"
},
{
"A1": "G",
(...)
我希望通过自定义键(“字母表”)对这个 JSON 字符串的“数据”部分进行排序,在上述情况下,这将是 site, A1, A5, A10
和实际上看起来像:
{
"Author": "joe",
"data": [
{
"site": "example1.com",
"A1": "G",
"A5": "G",
"A10": "G"
},
{
"site": "example2.com",
"A1": "G",
(...)
我在 Sorting FAQ 中阅读了有关自定义排序的信息但它只是提供了一种覆盖比较函数的方法,更不用说我不知道如何将其插入到我的代码中。
怎么做?
最佳答案
因为 python 字典是无序集合,所以使用 collections.OrderedDict
使用自定义排序:
from collections import OrderedDict
import json
allsites = [
{
'A5': 'G',
'A10': 'G',
'site': 'example1.com',
'A1': 'G'
},
{
'A5': 'R',
'A10': 'Y',
'site': 'example2.com',
'A1': 'G'
}
]
sort_order = ['site', 'A1', 'A5', 'A10']
allsites_ordered = [OrderedDict(sorted(item.iteritems(), key=lambda (k, v): sort_order.index(k)))
for item in allsites]
data = {'Author': "joe", 'data': allsites_ordered}
print json.dumps(data, indent=4, separators=(',', ': '))
打印:
{
"data": [
{
"site": "example1.com",
"A1": "G",
"A5": "G",
"A10": "G"
},
{
"site": "example2.com",
"A1": "G",
"A5": "R",
"A10": "Y"
}
],
"Author": "joe"
}
关于python - 如何自定义排序要在 json.dumps 中使用的字典列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18871217/