gpt4 book ai didi

python - 如何将 JSON 值放入列表 Python

转载 作者:太空宇宙 更新时间:2023-11-04 00:32:49 24 4
gpt4 key购买 nike

我有一个如下所示的 json 列表:

{
"callback": [{
"id": "R_puFk4fZ8m1lE4bD",
"set": "Default Response Set",
"ace": "asdf",
"date": "asdfdsa",
"1": "asdf",
"2": "s",
"3": "3",
"4": "1",
"zone": "0",
"long": "33.564498901367",
"lat": "-112.00869750977"
}
]
}

我的实际数据在列表中有很多 json 对象,我想知道如何将“日期”和“区域”之间的数字放在 json 中的单独列表中。 json 对象之间的数字不同,但它们始终在“日期”和“区域”值之间。

我会怎么做才能把它变成这样:

{
"callback": [{
"id": "R_puFk4fZ8m1lE4bD",
"set": "Default Response Set",
"ace": "asdf",
"date": "asdfdsa",
"Q": [
"1": "asdf",
"2": "s",
"3": "3",
"4": "1"
],
"zone": "0",
"long": "33.564498901367",
"lat": "-112.00869750977"
}
]
}

最佳答案

您可以通过集合成员资格对它们进行排序(如 PM 2Ring 所述,集合成员资格更快 O(1)):

def group_questions(source_dct):
meta_tags = {"id", "set", "ace", "date", "zone", "long", "lat"}

result_dct = {"Q": {}}
for key in source_dct:
if key not in meta_tags:
result_dct["Q"][key] = source_dct[key]
else:
result_dct[key] = source_dct[key]
return result_dct

结果(注意字典没有排序):

>>> print group_questions(dct)
{'set': 'Default Response Set',
'ace': 'asdf',
'zone': '0',
'long': '33.564498901367',
'Q': {'1': 'asdf',
'3': '3',
'2': 's',
'4': '1'},
'lat': '-112.00869750977',
'date': 'asdfdsa',
'id': 'R_puFk4fZ8m1lE4bD'}

关于python - 如何将 JSON 值放入列表 Python,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45174619/

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