python - 如何自定义排序要在 json.dumps 中使用的字典列表

标签 python json list sorting dictionary

我有一个类似的列表

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/

相关文章:

.net - 执行 POST 到 WCF 服务时出现 iOS 5 Json 错误 400

java - 如何为多个列表创建一个条件,仅显示具有相同值的数组

python - 找不到 django-pipeline amazon s3 collectstatic 文件

python - 根据值划分列表

Java - 解析json对象(输入结束于...的字符0)

json - 将 golang map[string] 接口(interface)存储到数据存储中的最佳方式

c++ - 为用户定义的 MyList 重载 operator<<

python - 从文本文件中提取特定记录并保存到 Python 中的新文件

python - 为什么 python 中的这个循环运行速度越来越慢?

java - 如何在 Python 测试框架中实现 TestNG 监听器?