0

Modified:

With the following student's scores file, how would I load the data and sum up score1, score3 in Python?

{"id": "1","student":"John", "dt": "1997-01-01 07:00:02", "score1": "38.28"} 
{"id": "2", "student":"Jane", "dt": "1997-01-01 07:00:02", "score1": "32.35"} 
{"id": "3", "student":"Richard", "dt": "1997-01-10 10:00:00", "score3": "22.92"}

output:

score1: 70.63
score3: 22.92
xerlil
  • 39
  • 2
  • There are a lot of ways you could go about it and you're asking for a very specific implementation, try asking a more pointed question like "how do I read text files into python" (though that has an answer already :https://stackoverflow.com/questions/14676265/how-to-read-text-file-into-a-list-or-array-with-python#14676357). How do you want them read in? Just the score or do you want all the data? What do you know about the formatting? – Gavin Achtemeier Jun 29 '17 at 01:08
  • 2
    Apparently by calling `get_stackoverflow_to_do_all_my_homework()` – donkopotamus Jun 29 '17 at 01:09

2 Answers2

0

file.txt:

{"id": "1","student":"John", "dt": "1997-01-01 07:00:02", "score1": "38.28"} 
{"id": "2", "student":"Jane", "dt": "1997-01-01 07:00:02", "score1": "32.35"} 
{"id": "3", "student":"Richard", "dt": "1997-01-10 10:00:00", "score3": "22.92"}

Do:

import json

scores = dict()
with open('file.txt') as filename:
    for line in filename.readlines():
       data = json.loads(line)
       score = [key for key in data.keys() if key.startswith('score')]
       if len(score) == 0:
           continue
       score = score[0]
       if score not in scores:
           scores[score] = 0
       scores[score] += float(data[score])

for k, v in scores.items():
    print('{}: {}'.format(k, v))

Ouput:

score1: 70.63
score3: 22.92
glegoux
  • 3,505
  • 15
  • 32
0

Using the built-in library json you can decode JSON into Python objects. If you use this data:

[
    {"id": "1","student":"John", "dt": "1997-01-01 07:00:02", "score1": "38.28"}, 
    {"id": "2", "student":"Jane", "dt": "1997-01-01 07:00:02", "score1": "32.35"}, 
    {"id": "3", "student":"Richard", "dt": "1997-01-10 10:00:00", "score3": "22.92"}
]

Note the [...] and , in the data so it loads as a list.

Then the script below could do the job.

import json
from math import fsum

data = json.load(open("data.json")) # Load the data
sums = {}
for person in data: # Loop over pieces of data
    # Add any names starting with "score" to sums
    for key in person.keys(): # Loop over names
        if not key[:5] == "score":
            continue # No, not starting with score, skip it
        # Use math.fsum to add the value known to the score, and set it.
        sums[key] = fsum([sums.get(key, 0.0), float(person[key])])
for k, v in sums.items():
    # Print out the data
    print("%s: %.02f" % (k, v))

I added explanations in the comments. Tested in IDLE 3.6.1.

Nick S.
  • 21
  • 5