Python Forum
convert a json file to a python dictionnary of array - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: convert a json file to a python dictionnary of array (/thread-21008.html)



convert a json file to a python dictionnary of array - Reims - Sep-10-2019

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


RE: convert a json file to a python dictionnary of array - buran - Sep-10-2019

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


RE: convert a json file to a python dictionnary of array - Reims - Sep-10-2019

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