Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python csv list compare and addition

Parsing & Adding Client Data

Data:
('Client 1', '13.2')
('Client 1', '22.4')
('Client 1', '1.2')
('Client 2', '3.4')
('Client 3', '12.3')
('Client 3', '3.221')
('Client 4', '234.44')

Trying to write the proper loop and adding feature to get the right output.

Goal Result:

Client 1: 36.8
Client 2: 3.4
Client 3: 15.521
Client 4: 234.44

This is the code I finally got to list the data correctly. Where do I go from here to get the result. I have tried a number of different loops with no success.

import csv

with open('clientdata.csv') as csvfile:
    reader = csv.DictReader(csvfile)
    numbers = []
    for row in reader:
       print(row['Client Name'], row['Earnings'])
like image 459
Troy Wilson Avatar asked Sep 20 '26 15:09

Troy Wilson


1 Answers

You can solve it by using a format string (%.2f will have 2 decimal places) and dictionary keeping track of who makes how much.

clients = {}
with open('clientdata.csv') as csvfile:
    reader = csv.DictReader(csvfile)
    numbers = []
    for row in reader:
       name = row['Client Name']
       earnings = float(row['Earnings'])
       if name in clients:
           clients[name] += earnings
       else:
           clients[name] = earnings
    for client in sorted(clients):
          print("%s:%.2f" % (client, clients[client]))
like image 103
mattsap Avatar answered Sep 23 '26 06:09

mattsap