Calculating the median

Calculating the median

Given a files salaries.csv with this structure:
City,Job,Salary
Delhi,Doctors,500
Delhi,Lawyers,400
Delhi,Plumbers,100
London,Doctors,800
London,Lawyers,700
London,Plumbers,300
Tokyo,Doctors,900
Tokyo,Lawyers,800
Tokyo,Plumbers,400
...
... print the median salary of each profession.

Sample output

Plumbers 500
Lawyers 700
Doctors 800
...
 
 
 

solution

 

import csv
from collections import defaultdict

f= open("salaries.csv","r")
d = defaultdict(list)
reader = csv.reader(f)
reader.next()
for row in reader:
    d[row[1]].append(float(row[2]))  

for k,v in d.iteritems():
    print (k,sorted(v)[len(v) // 2])

No comments:

Post a Comment