gpt4 book ai didi

python - 从 Python 中的字典列表创建 JSON

转载 作者:太空宇宙 更新时间:2023-11-04 02:56:43 25 4
gpt4 key购买 nike

我有一个 friend 的项目数据:

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 放在第二个位置并且打乱了下一个排序过程,而且它不起作用。

最佳答案

Python 字典是未排序的。您有几个选择。

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

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

使用维护字典条目创建顺序的类型:

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

或者最简单的方法是,按照您想要的顺序将它们添加到数组/列表的第一位。

关于python - 从 Python 中的字典列表创建 JSON,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42123104/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com