Learn practical skills, build real-world projects, and advance your career
Created 3 years ago
Exercise - Processing CSV files using a dictionary of lists
import os
import urllib.request as url
url1 = 'https://gist.githubusercontent.com/aakashns/257f6e6c8719c17d0e498ea287d1a386/raw/7def9ef4234ddf0bc82f855ad67dac8b971852ef/loans1.txt'
url2 = 'https://gist.githubusercontent.com/aakashns/257f6e6c8719c17d0e498ea287d1a386/raw/7def9ef4234ddf0bc82f855ad67dac8b971852ef/loans2.txt'
url3 = 'https://gist.githubusercontent.com/aakashns/257f6e6c8719c17d0e498ea287d1a386/raw/7def9ef4234ddf0bc82f855ad67dac8b971852ef/loans3.txt'
url.urlretrieve(url1,'./loans/loans1.txt')
url.urlretrieve(url2,'./loans/loans2.txt')
url.urlretrieve(url3,'./loans/loans3.txt')
('./loans/loans3.txt', <http.client.HTTPMessage at 0x20dd9742df0>)
def read_csv(path):
#reading the file
with open(path) as f:
file_content=f.readlines()
#extracting the header
headers=file_content[0].strip().split(',')
#converting rest of the file into list of list of loans [[1st loan],[2 loan],....]
item_list=[]
for line in file_content[1:]:
line=line.strip().split(',') #reading file line-by-line
loans=[]
for item in line: #iterating over details of single loan
if item=='':
item=0.0
loans.append(float(item)) #making list of details
item_list.append(loans) #appending to the final loans sheet
loan_dict={}
k=0
for header in headers:
item=[]
for j in range(len(item_list)): #iterating through all loans
item.append(item_list[j][k]) #taking single column items and appending
loan_dict[header]=item
k+=1
return loan_dict