Skip to content
Advertisement

Converting csv with several items to a json with several elements in Python

Hello I have been exploring Python to do a task in which I have the following csv file:

enter image description here

My goal was to get a json with the following structure:

JavaScript

I was looking at a suggestion on how to convert csv files to json using the following code

JavaScript

However the reader is not identifying each item in the csv as an element and instead is only giving an output with a single element like this:

JavaScript

How should I modify my csv file/ python code in order to obtain a list of elements with each item from the csv?

Advertisement

Answer

This is a quick solution, there is scope for improvement.
Check if this code works for you, let me know in case of any issues/confusion:

JavaScript

Output:

[{“1”: [{“Day”: “1”, “Result”: “4”, “Accuracy”: “80”}, {“Day”: “2”, “Result”: “4”, “Accuracy”: “80”}, {“Day”: “3”, “Result”: “5”, “Accuracy”: “100”}], “2”: [{“Day”: “1”, “Result”: “3”, “Accuracy”: “60”}, {“Day”: “2”, “Result”: “4”, “Accuracy”: “80”}, {“Day”: “3”, “Result”: “5”, “Accuracy”: “100”}], “3”: [{“Day”: “1”, “Result”: “2”, “Accuracy”: “40”}, {“Day”: “2”, “Result”: “2”, “Accuracy”: “40”}, {“Day”: “3”, “Result”: “3”, “Accuracy”: “60”}]}]

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