Reorder JSON in python

Question:

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', ....}
Asked By: userHG

||

Answers:

Here is my solution. Know for the future that you are expected to show your efforts in solving the problem when asking a question. You can’t always expect everything done for you.

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]}

You can also do this with one line:

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()}

In both of these examples, the output of print(result) would be:

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

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.

Answered By: RoadRunner

Lets say your json_input is your json.

result = {}
for i,(_id, _brand) in enumerate(zip(json_input["id"].values(), json_input["brand"].values())): 
     result.update({i: {"brand": _brand, "id": _id}}) 
Answered By: GraphicalDot
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.