02 May 2022



Input CSV File:

country, population
Usa, 1273
Usa, 4343
Usa, 1240
Uk, 7879
Uk, 3224
Uk, 4342
Tr, 6565
Tr, 7889
Tr, 1980

========================
import csv

index = {}
with open('/tmp/data.csv') as f:
    cr = csv.reader(f)
    next(cr) # skip header row
    for row in cr:
        index.setdefault(row[0], []).append(int(row[1]))

print("['country', 'avgPop']")
for c, v in index.items():
    print("['{}', '{}']".format(c, int(sum(v) / len(v))))


Result:

['country', 'avgPop']
['Usa', '2285']
['Uk', '5148']
['Tr', '5478']

No comments:

Post a Comment