如何自定义要在json.dumps中使用的dict列表 [英] How to custom-sort a list of dict to use in json.dumps
问题描述
我有一个类似于
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:
This outputs the following JSON:
{
"Author": "joe",
"data": [
{
"A1": "G",
"A10": "G",
"A5": "G",
"site": "example1.com"
},
{
"A1": "G",
(...)
我希望这个JSON字符串的数据部分可以通过自定义键(字母表),在这种情况下,这将是网站,A1,A5,A10
,实际上看起来像:
I would like the "data" section of this JSON string to be sorted via a custom key ("alphabet"), in the case above this would be site, A1, A5, A10
and actually look like:
{
"Author": "joe",
"data": [
{
"site": "example1.com",
"A1": "G",
"A5": "G",
"A10": "G"
},
{
"site": "example2.com",
"A1": "G",
(...)
我在排序FAQ 但它只是提供一种方法来覆盖比较功能,更不用说我不知道如何将其插入到我的代码中。
I read about custom sorting in the Sorting FAQ but it just gives a way to override the comparison function, not to mention that I do not know how to insert this into my code.
如何做?
推荐答案
由于python dicts是无序集合,请使用 collections.OrderedDict
具有自定义排序:
Since python dicts are unordered collections, use collections.OrderedDict
with a custom sort:
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"
}
这篇关于如何自定义要在json.dumps中使用的dict列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!