当前位置: 代码迷 >> python >> 从 Python 中的字典列表创建 JSON
  详细解决方案

从 Python 中的字典列表创建 JSON

热度:85   发布时间:2023-06-13 13:42:55.0

我和一个朋友有一个项目的数据:

arr = [{'Key':'Key 1', 'SecondKey':'SecondKey 1', 'ThirdKey':'Thirdkey 1', 'Value':100},
   {'Key':'Key 1', 'SecondKey':'SecondKey 1', 'ThirdKey':'ThirdKey 2', 'Value':130},
   {'Key':'Key 1', 'SecondKey':'SecondKey 2', 'ThirdKey':'ThirdKey 1', 'Value':230},
   {'Key':'Key 1', 'SecondKey':'SecondKey 2', 'ThirdKey':'ThirdKey 2', 'Value':300},
   {'Key':'Key 2', 'SecondKey':'SecondKey 4', 'ThirdKey':'ThirdKey 1', 'Value':111},
   {'Key':'Key 2', 'SecondKey':'SecondKey 2', 'ThirdKey':'ThirdKey 2', 'Value':400},
   {'Key':'Key 2', 'SecondKey':'SecondKey 1', 'ThirdKey':'ThirdKey 2', 'Value':230}
   ] 

我试过这样的功能:

def array_to_dict(arr, classification):
    dct = tree()
    for d in arr:
        dct[d["Key"]]=(d)
    pprint.pprint(dct)

def tree():
    return defaultdict(tree)

def array_to_dict_recursive(arr, classification):
    result = defaultdict(arr)
    for v, k in arr:
        result[k].append(v)
    final_result = [{'type': k, 'items': v} for k, v in result.items()]
    print (str(final_result))

def array_cool(arr):
    #pprint.pprint(arr)
    arr.sort(key=operator.itemgetter('Key'))
    pprint.pprint(arr)
    list1= []
    print("")
    for key, items in itertools.groupby(arr, operator.itemgetter('Key')):
        list1.append(list(items))
    pprint.pprint(list1)

我希望它以这种方式显示为 JSON 文件:

{
"Key 1": {
    "SecondKey 2": {
        "ThirdKey 2": [
            {
                "Key": "Key 1",
                "Value": 300,
                "SecondKey": "SecondKey 2",
                "ThirdKey": "ThirdKey 2"
            }
        ],
        "ThirdKey 1": [
            {
                "Key": "Key 1",
                "Value": 230,
                "SecondKey": "SecondKey 2",
                "ThirdKey": "ThirdKey 1"
            }
        ]
    },
    "SecondKey 1": {
        "ThirdKey 2": [
            {
                "Key": "Key 1",
                "Value": 130,
                "SecondKey": "SecondKey 1",
                "ThirdKey": "ThirdKey 2"
            }
        ],
        "ThirdKey 1": [
            {
                "Key": "Key 1",
                "Value": 100,
                "SecondKey": "SecondKey 1",
                "ThirdKey": "ThirdKey 1"
            }
        ]
    }
},
"Key 2": {
    "SecondKey 4": {
        "ThirdKey 1": [
            {
                "Key": "Key 2",
                "Value": 111,
                "SecondKey": "SecondKey 4",
                "ThirdKey": "ThirdKey 1"
            }
        ]
    },
    "SecondKey 2": {
        "ThirdKey 2": [
            {
                "Key": "Key 2",
                "Value": 400,
                "SecondKey": "SecondKey 2",
                "ThirdKey": "ThirdKey 2"
            }
        ]
    },
    "SecondKey 1": {
        "ThirdKey 2": [
            {
                "Key": "Key 2",
                "Value": 230,
                "SecondKey": "SecondKey 1",
                "ThirdKey": "ThirdKey 2"
            }
        ]
    }
}

}

我尝试过排序,但是排序将 Key 放在第二个位置,并干扰了下一个排序过程,它不起作用。

尝试

print json.dumps(arr, indent=4, sort_keys=True)

有关更多信息,请参阅文档:

json.dumps(obj, skipkeys=False, ensure_ascii=True, check_circular=True, allow_nan=True, cls=None, indent=None, separators=None, encoding="utf-8", default=None, sort_keys=False, **千瓦)

Python dicts 是未排序的。 你有几个选择。

使用将排序应用于标准字典的工具,例如:

import json
print json.dumps(thedict, indent=4, sort_keys=True)

使用保持 dict 条目创建顺序的类型:

from collections import OrderedDict
d = OrderedDict()
d[KEY] = VALUE
d[KEY][SUBKEY] = VALUE
etc.

或者最简单的,只需按照您想要的顺序将它们添加到数组/列表中。

这是你想要的第一次尝试。 它会让你开始,然后你可以简化它并让它变得漂亮。 关键点:

  • json.dumps()按照看到的顺序输出字典键,因此明确排序的 OrderedDict 可能是您获得它的唯一方法。
  • 您的结果与输入的数据结构不同,因此您必须构建它
  • Python 和 JSON 中的字典没有有序键。 因此,当您将结果导入其他内容时,订单可能会丢失。
  • 这段代码非常低效,并且可能在大型数据集上表现不佳。

您的数据结构:

  • 每个Key字典,按顺序排序
    • 每个SecondKey字典,反向排序
      • 每个ThirdKey dict ,反向排序
        • 一个包含每个值的字典(没有对值进行排序)的列表,其中包含这些已排序的键和值
          • Key1:外循环的Key
          • 值:当前项目的值
          • SecondKey:来自外循环的SecondKey
          • 第三键:来自外循环的ThirdKey键值

.

from collections import OrderedDict
import json

arr = [{'Key':'Key 1', 'SecondKey':'SecondKey 1', 'ThirdKey':'ThirdKey 1', 'Value':100},
    {'Key':'Key 1', 'SecondKey':'SecondKey 1', 'ThirdKey':'ThirdKey 2', 'Value':130},
    {'Key':'Key 1', 'SecondKey':'SecondKey 2', 'ThirdKey':'ThirdKey 1', 'Value':230},
    {'Key':'Key 1', 'SecondKey':'SecondKey 2', 'ThirdKey':'ThirdKey 2', 'Value':300},
    {'Key':'Key 2', 'SecondKey':'SecondKey 4', 'ThirdKey':'ThirdKey 1', 'Value':111},
    {'Key':'Key 2', 'SecondKey':'SecondKey 2', 'ThirdKey':'ThirdKey 2', 'Value':400},
    {'Key':'Key 2', 'SecondKey':'SecondKey 1', 'ThirdKey':'ThirdKey 2', 'Value':230}
    ]

def arr_to_ordereddict():
    d = OrderedDict()
    keys = set(a['Key'] for a in arr)
    #print(sorted(keys))
    for k1 in sorted(keys):
        k1_dict = OrderedDict()
        d[k1] = k1_dict
        arr2 = [a for a in arr if a['Key'] == k1]
        keys2 = set(a['SecondKey'] for a in arr2)
        #print('\t', k1, sorted(keys2, reverse=True))
        for k2 in sorted(keys2, reverse=True):
            k2_dict = OrderedDict()
            k1_dict[k2] = k2_dict
            arr3 = [a for a in arr if a['SecondKey'] == k2]
            keys3 = set(a['ThirdKey'] for a in arr3)
            #print('\t\t', k1, k2, sorted(keys3, reverse=True))
            for k3 in sorted(keys3, reverse=True):
                k3_list = []
                k2_dict[k3] = k3_list
                for item in (a for a in arr3 if a['ThirdKey'] == k3):
                    value_dict = OrderedDict()
                    value_dict['Key'] = k1
                    value_dict['Value'] = item['Value']
                    value_dict['SecondKey'] = k2
                    value_dict['ThirdKey'] = k3
                    k3_list.append(value_dict)
    return d

print(json.dumps(arr_to_ordereddict(), indent=4))
  相关解决方案