Python: Working with CSV file --> How would I write a function that will return a list of lists, with the frequency and the zip code. Organize the list in decreasing order of frequency (Print the number of suppliers and the zip code for the 10 most common zip codes in the file. )
An example of three items from the 720 zip codes results in: [ ... [9, '65616'], [8, '94573'], [8, '63103'] ...]. This tells us that Branson, Missouri, has 9 beer or wine suppliers to the state, and Rutherford, California, has 8.
Below is the python code for the information stored in file named k.csv
import csv
'''final list'''
k=[]
with open('k.csv', newline='') as csvfile:
spamreader = csv.reader(csvfile, delimiter=',', quotechar='|')
for row in spamreader:
m=[]
'''temporary list'''
m.append(int(row[0]))
m.append(row[1])
k.append(m)
p=sorted(k,key=lambda x: x[0],reverse=True)
''' sorting the list in reverse using inbuilt function'''
print(p)
Below is the csv file which would be read
8,101901
9,110086
7,908211
8,192000
Below is the output of the program return above
Output-:
Get Answers For Free
Most questions answered within 1 hours.