Question

In: Computer Science

I am trying to create a program that reads from a csv file and finds the...

I am trying to create a program that reads from a csv file and finds the sum of total volume in liters of liquor sold from the csv file by county and print that list out by county in descending order. Currently my program runs and gives me the right answers but it is not in descending order. I tried this:

    for county, volume in sorted(sums_by_volume.items(), key=lambda x: x[1], reverse=True):

        index +=1

        print("{}. {} {:.2f}".format(county, sums_by_volume[county]))

    

When I run this, it gives me an IndexError: Replacement index 2 out of range for positional args tuple.

Below is my entire code. I don't know what I am doing wrong. Could you please help?

from csv import reader

#Asks for name of input files

#Opens and reads the fiel with a CSV reader

#Sums the sales by volumn for each rows county

#Sum total Sales in Iowa

#Prints the total country sales ordered by volume

UserInput = input("Please enter a file name: ")

sums_by_volume = {}

index = 0

if (UserInput == 'Iowa-Liquor-Sales-2019.csv'):

    inputFile = UserInput

    print('Success! File Found!')

else:

    print ('No Such File Found! Please Restart The Program And Enter A New File')

    quit()

with open(inputFile, 'r') as csvFile:

    csvreader = reader(csvFile)

    headers = next(csvreader)

    

    for row in csvreader:

        COUNTY_NAME = row[9].upper()

        VOLUME_IN_LITERS = float(row[22])

        if COUNTY_NAME not in sums_by_volume:

           # print('This is a test message')

            sums_by_volume[COUNTY_NAME] = 0.0

        sums_by_volume[COUNTY_NAME] += VOLUME_IN_LITERS

    

    #SortedSum = sorted(sums_by_volume.values(), reverse = True)

    #print(SortedSum)

    

    for county, volume in sorted(sums_by_volume.items(), key=lambda x: x[1], reverse=True):

        index +=1

        print("{}. {} {:.2f}".format(county, sums_by_volume[county]))

        #print(SortedSum, + " ", COUNTY_NAME)

        

print('End of Program')



Solutions

Expert Solution

Hi friend,

You did everything great, but there is a very minute mistake while you are printing the values, let me help you regarding this,

Index error:

Index error usally occurs when we are trying to fetch the data that is not present or which is out of bounds.

so your program encounterd an Index error, the first thing we need to do is, we should find where we are trying to fetch data that is out of bounds.

After travesing the code you have written, I found this line which is causing this Index out of bounds error

line in your code that is giving error

print("{}. {} {:.2f}".format(county, sums_by_volume[county]))

position of the line in code: from bottom 3rd line

Note: the red colored {} is causing you index out of bounds error

The error you commited is

you are giving 3 placeholders ( {}. {} {:2f} ) but you are filling them with 2 values (.format(country, sum_by_volume[country]) , so third placeholder is waiting for value which you did not specify that is the reason you are getting index out of bounds error.

Correct line of code that should be replaced with the above line

print("{}. {:.2f}".format(county, sums_by_volume[county]))

apart from this minute mistake you did a great job, please check now after changing the code if you still have any problem please mention your query in comment box, I will reach to you as soon as possible,

If your code works fine please given a THUMBS UP,

Thank you in advance. :)


Related Solutions

I am trying to create a makefile for the following program in Unix. The C++ program...
I am trying to create a makefile for the following program in Unix. The C++ program I am trying to run is presented here. I was wondering if you could help me create a makefile for the following C++ file in Unix and show screenshots of the process? I am doing this all in blue on putty and not in Ubuntu, so i don't have the luxury of viewing the files on my computer, or I don't know how to...
In this programming assignment, you will write a program that reads in the CSV file (passenger-data-short.csv),...
In this programming assignment, you will write a program that reads in the CSV file (passenger-data-short.csv), which contains passenger counts for February 2019 on 200 international flights. The data set (attached below) is a modified CSV file on all International flight departing from US Airports between January and June 2019 reported by the US Department of Transportation. You write a program that give some summary statistics on this data set. Create a header file named flights.h. In this file, you...
I am trying to make a program in Python that opens a file and tells you...
I am trying to make a program in Python that opens a file and tells you how many lines, vowels, consonants, and digits there are in the file. I got the print out of lines, digits, and consonants, but the if statement I made with the vowels list isn't recognizing them. How can I make the vowels go through the if statement with the list? Am I using the wrong operator? Here is my program #Assignment Ch7-1 #This program takes...
Create a program that parses a CSV file of product data and prints the items with...
Create a program that parses a CSV file of product data and prints the items with a price that is less than or equal to that input by the user. • Your program should take two arguments: an input file to process and a price limit. • Print only the names of each item to stdout that have a price less than or equal to the given limit. • If the given file does not exist or cannot be opened,...
Java: create a program that reads in a piece of DNA sequence from a sequence file...
Java: create a program that reads in a piece of DNA sequence from a sequence file (dna.seq) (alternatively you can use the getRandomSeq(long) method of the RandomSeq class to generate a piece of DNA sequence), and then print out all the codons in three forward reading frames. Design a method called codon() that can be used to find all the codons from three reading frames. The method will take in an argument, the reading frame (1, 2, or 3), and...
UNSURE HOW TO PARSE: I am trying to parse a website with a CSV : import...
UNSURE HOW TO PARSE: I am trying to parse a website with a CSV : import csv import requests as r from bs4 import BeautifulSoup urltoget = 'a.ttu.edu/2019c/isqs6339/http://drd.bhw1/index.php' filepath = 'C:\\Users\\Zuliat\\Desktop\\test123.csv' res = r.get(urltoget) res.content if res.status_code == 200: print (' request is good') else: print (' bad request, retrieved code' + str(res.status_code))    print (res.content) soup = BeautifulSoup(res.content,'lxml') print(soup.title) They are responding with a message Line 1
How do I write a C++ program to call a frequency table from a csv file,...
How do I write a C++ program to call a frequency table from a csv file, using vector? Data given is in a csv file. Below is part of the sample data. Student ID English Math Science 100000100 80 90 90 100000110 70 60 70 100000120 80 100 90 100000130 60 60 60 100000140 90 80 80
Create a Python program that: Reads the content of a file (Vehlist.txt) The file contains matching...
Create a Python program that: Reads the content of a file (Vehlist.txt) The file contains matching pairs of vehicle models and their respective makes Separate out the individual make and model on each line of the file Add the vehicle make to one list, and the vehicle model to another list; such that they are in the same relative position in each list Prompt the user to enter a vehicle model Search the list containing the vehicle models for a...
C++ Assignment Hi, I need to create a program that: 1.Reads a source file (.txt) with...
C++ Assignment Hi, I need to create a program that: 1.Reads a source file (.txt) with following information: 1,2,3,4,5 red,blue,green,yellow,orange left, right,front, back 2. After having program read the .txt file, output the above information in categories of Symbol, Token Type, and Count : Example: Symbol---Token Type (data type)----Count (how many times symbol appeared in .txt file) =========================================================================== 1 ----digit ----1 2 ----digit ----1 red ----color ----1 blue ----color ----1 left ----direction ----1 right ----direction    ----1
C++ Assignment Hi, I need to create a program that: 1.Reads a source file (.txt) with...
C++ Assignment Hi, I need to create a program that: 1.Reads a source file (.txt) with following information: 1,2,3,4,5 red,blue,green,yellow,orange left, right,front, back 2. After having program read the .txt file, output the above information in categories of Symbol, Token Type, and Count : Example: Symbol---Token Type (data type)----Count (how many times symbol appeared in .txt file) =========================================================================== 1 ----digit ----1 2 ----digit ----1 red ----color ----1 blue ----color ----1 left ----direction ----1 right ----direction    ----1
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT