Python Forum

Full Version: convert a json file to a python dictionnary of array
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hi there, i m a newbee so excuse if my question looks dummy.

so i have a json file which look like this

Output:
[{'_id': '1', 'date': '2019-09-07', 'name': 'abi', 'value': 0, 'unit': '°C'}, {'_id': '2', 'date': '2019-09-08', 'name': 'allo', 'value': 3, 'unit': '°F'}, {'_id': '3', 'date': '2019-09-09', 'name': 'ali', 'value': 0, 'unit': '°C'}]
and i want to read this json file in order to convert it into a dictionnary of array which looks like

Output:
[{'_id': [ '1', '2','3']}, {'date': [ '2019-09-07', '2019-09-08','2019-09-09']}, {'name': [ 'abi', 'allo','ali']}, {'value': [ '0', '3','0']}, {'unit': [ '°C', '°F','°C']},]
Thank you in advance
what have you tried? Note that so called json that you have is not valid one. it looks like already converted to JSON object in python
(Sep-10-2019, 10:26 AM)buran Wrote: [ -> ]what have you tried? Note that so called json that you have is not valid one. it looks like already converted to JSON object in python

thanks Buran,
i find out this solution
from collections import defaultdict

data = [{'_id': '1', 'date': '2019-09-07', 'name': 'abi', 'value': 0, 'unit': '°C'},
{'_id': '2', 'date': '2019-09-08', 'name': 'allo', 'value': 3, 'unit': '°F'},
{'_id': '3', 'date': '2019-09-09', 'name': 'ali', 'value': 0, 'unit': '°C'}]

result = defaultdict(list)
for i in data:
    for k, v in i.items():
        result[k].append(v)
print(result)