30 lines
1.1 KiB
Python
30 lines
1.1 KiB
Python
def table(data, head):
|
|
# Formats the data into a nice table in a string
|
|
t = "{:^25}|{:^10}|\n".format(head[0],head[1])
|
|
t += ("-"*len(t)+"\n")
|
|
for n,p in data.items():
|
|
t += ("{:^25}|{:^10}|\n".format(n, p))
|
|
return(t)
|
|
|
|
def main():
|
|
with open('norway_municipalities_2017.csv') as f:
|
|
# we will make a dict where the the kei is the district and the value the population
|
|
d = {}
|
|
# assume the csv file always has a header
|
|
l_iter = iter(f)
|
|
l_iter.__next__()
|
|
for l in l_iter:
|
|
# we get a list where 0 is the kommune name, 1 is what fylke it is in and 2 is the population
|
|
ll = l.strip("\n").split(',')
|
|
name = ll[1]
|
|
if name in d.keys():
|
|
d.update({name: d.get(name) + int(ll[2])})
|
|
else:
|
|
d.update({name: int(ll[2])})
|
|
|
|
head = ["District", "Population"]
|
|
res = {key: val for key, val in sorted(d.items(), key = lambda ele: ele[1], reverse=True)}
|
|
print(table(res, head))
|
|
|
|
if __name__ == "__main__":
|
|
main() |