由于python
dicts是无序集合,请
collections.OrderedDict与自定义排序一起使用:
from collections import OrderedDictimport jsonallsites = [ { '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"}


