Skip to content
Advertisement

Reorder JSON in python

Hello I got a JSON in python :

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

I need to reorder it to have this JSON :

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

Advertisement

Answer

You could use a collections.defaultdict to group by the inner dictionaries keys:

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)

Output:

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

Or if you want a normal dict type:

print(dict(result))

Output:

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

Note: defaultdict is a subclass of dict, so the latter option is not needed.

User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement