In: Computer Science
Python: I am currently a function that will return a list of lists, with the frequency and the zip code. However, I am having a difficult time organizing the list in decreasing order of frequency. We are asked to use sort () and sorted () instead of lambda. The function will find 5 digit zip codes, and when it sees a 9-digit zip code, the function needs to truncate the last 4 digits. The following is an example of the outlook.
[ ... [9, '65616'], [8, '94573'], [8, '63103'] ...]
This is what I have so far:
import csv
updated_list = []
with open('Missouri_Beer_Wine.csv', 'r') as file:
reader = csv.reader (file, delimiter=',', quotechar='|')
for row in reader:
list = []
list.append(int(row[0]))
list.append(row[1])
updated_list.append (list)
new_list = sorted(updated_list)
print (new_list)
I am running into an error where it states there is a ValueError: invalid literal for int() with base 10: 'Business Name'. How would I go about this?
From your question I understood that you need to find the frequency of zip codes that occur and return the frequency and zip code as a list. eg: [ [ frequency-1 , zipcode-1 ] , [ frequency-2 , zipcode-2 ] , .... ]
so for this purpose
In the below code I assume the quotechar value as " . you can use the quotechar value according to the csv file.
import csv
with open('Missouri_Beer_Wine.csv', 'r') as file:
reader = csv.reader (file, delimiter=',', quotechar='"')
#initializing the dictionary for storing zipcode value
zip_dict = {}
for row in reader:
# assuming row1 contains the zipcode
# truncating the zip code to 5 values
zipcode = row[1]
truncated_zip=zipcode[:5]
# print(truncated_zip)
# storing zipcode value along with count in a dictionary
if not truncated_zip in zip_dict:
zip_dict[truncated_zip] = 1
# if dictionary contains the zipcode we increment the value by 1
else:
zip_dict[truncated_zip] += 1
# now zip_dict contains zipcodes along with its frequncies
# converting it to a list of list using single line "list comprehension"
output_list = [[val,key] for key, val in zip_dict.items()]
# finally sort the list in reverse manner
final_output_list = sorted(output_list,reverse=True)
print(final_output_list)