在python中重新排序JSON



你好,我在python中得到了一个JSON:

{'id': {'0': 'AAPL', '1': 'MIC', '2': 'GOO', '3': 'AMZ'}, 'brand': {'0': 'apple', '1': 'microsoft', '2': 'google', '3': 'amazon'}}

我需要对它进行重新排序以获得此JSON:

{'0': { id:'AAPL', brand:'apple'}, 1 : {id:'MIC', brand:'microsoft', ....}

您可以使用collections.defaultdict按内部字典键进行分组:

from collections import defaultdict
d = {'id': {'0': 'AAPL', '1': 'MIC', '2': 'GOO', '3': 'AMZ'}, 'brand': {'0': 'apple', '1': 'microsoft', '2': 'google', '3': 'amazon'}}
result = defaultdict(dict)
for k1, v1 in d.items():
for k2, v2 in v1.items():
result[k2][k1] = v2
print(result)

输出:

defaultdict(<class 'dict'>, {'0': {'id': 'AAPL', 'brand': 'apple'}, '1': {'id': 'MIC', 'brand': 'microsoft'}, '2': {'id': 'GOO', 'brand': 'google'}, '3': {'id': 'AMZ', 'brand': 'amazon'}})

或者,如果您想要普通的dict类型:

print(dict(result))

输出:

{'0': {'id': 'AAPL', 'brand': 'apple'}, '1': {'id': 'MIC', 'brand': 'microsoft'}, '2': {'id': 'GOO', 'brand': 'google'}, '3': {'id': 'AMZ', 'brand': 'amazon'}}

注意:defaultdictdict的子类,因此不需要后一个选项。

这是我的解决方案。要知道,在未来提出问题时,你应该表现出你在解决问题方面的努力。你不可能总是期望一切都为你完成。

data = {'id': {'0': 'AAPL', '1': 'MIC', '2': 'GOO', '3': 'AMZ'}, 'brand': {'0': 'apple', '1': 'microsoft', '2': 'google', '3': 'amazon'}}
result = {}
for k in data['id'].keys():
result[k] = {'id': data['id'][k], 'brand': data['brand'][k]}

你也可以用一行代码做到这一点:

data = {'id': {'0': 'AAPL', '1': 'MIC', '2': 'GOO', '3': 'AMZ'}, 'brand': {'0': 'apple', '1': 'microsoft', '2': 'google', '3': 'amazon'}}
result = {k : {'id': data['id'][k], 'brand': data['brand'][k]} for k in data['id'].keys()}

在这两个例子中,print(result)的输出都是:

{'0': {'id': 'AAPL', 'brand': 'apple'}, '1': {'id': 'MIC', 'brand': 'microsoft'}, '2': {'id': 'GOO', 'brand': 'google'}, '3': {'id': 'AMZ', 'brand': 'amazon'}}

假设您的json_input就是您的json。

result = {}
for i,(_id, _brand) in enumerate(zip(json_input["id"].values(), json_input["brand"].values())): 
result.update({i: {"brand": _brand, "id": _id}}) 

最新更新