Issue
def main():
salesData= readData('icecream.txt')
print(salesData)
#printReport(salesData)
# Reads the tabular data
# @param filename name of the input file
# @return a dictionary whose keys are ice cream flavors and whose values are sales data.
def readData(filename):
# Create an empty dictionary.
salesData={}
infile=open(filename, "r")
# Read each record from the file.
for line in infile:
fields=line.split(":") # what is field datatype
flavor=fields[0]
salesData[flavor]=buildList(fields)
#print("SalesData", salesData)
#print()
#print()
infile.close()
return salesData
# Builds a list of store sales contained in the fields split from a string.
# @param fields a list of strings comprising the record fields
# @return a list of floating-point values
def buildList(fields):
storeSales= []
for i in range (1, len(fields)):
sales=float(fields[i])
storeSales.append(sales)
#print('StoreSales', storeSales)
#print()
return storeSales
# Prints a sales report.
def printReport(salesData):
numStores=0
#print the dictionary first without the totals?
#call print report
main()
When I run the program in its current state, it will give me the following output:
{'chocolate': [10225.25, 9025.0, 9505.0], 'strawberry': [9285.15, 8276.1, 8705.0], 'cookie dough': [7901.25, 4267.0, 7056.5], 'rocky road': [6700.1, 5012.45, 6011.0], 'vanilla': [8580.0, 7201.25, 8900.0]}
However, I NEED it to look like this:
chocolate 10225.25 9025.0 9505.0 Total: 28755.25
vanilla 8580.0 7201.25 8900.0 Total: 24681.25
rocky road 6700.1 5012.45 6011.0 Total: 17723.55
strawberry 9285.15 8276.1 8705.0 Total: 26266.25
cookie dough 7901.25 4267.0 7056.5 Total: 19224.75
**42691.75 33781.8 40177.5**
Clean, organized, tabbed, perfect alignment. I don't know how to pull the data from the dictionary in a clean manner. I have to, in addition, add the totals for chocolate, etc. and the 1st, 2nd and 3rd columns. Presentation is important. It's not merely a "how do I output the data" but, "how do I output the data with a clean presentation." I was thinking of using nested for loops, or maybe something with a for loop. But where that for loop goes, or how I use it to print out the dictionary data cleanly how I want it to look like is beyond me. I've looked at other questions asked, but nothing comes close to this level of tabulation, organization and printing specifics for data coming from a dictionary. I've also attempted the often cited "for key, val in X.items():" but that hasn't worked for me. I don't even know where to start with that function and its confusing beyond belief. Where would I put it? How would I name it? Where would I go from there? Not to mention I have columns to add, and rows to add. This is a very specific question. Thank you.
Solution
Python has an excellent mini-language specifically for string formatting. This is what should be used.
You know that you want your format to be
flavor sell1 sell2 sell3 Total: total sells
Which would equate to the following string format:
"{} \t {} \t {} \t {} \t Total: {}"
So now that you know your format, the next step is to apply this format to every key, value
pair in your dictionary. Use a for loop to iterate over each key, value
pair.
for key, value in dictionary.items():
print("{} \t {} \t {} \t {} \t Total: {}".format(...))
The last thing left to do is to fill in the blanks. You know that the key
s in your dict()
are the flavors, so the first parameter to format()
would be the key
variable:
.format(key, ...)
Next you need the three values from your key
's, values. We could index each value out of of value
:
.format(key, value[0], value[1], value[2], ...)
Bu that's a bit verbose, and Python had a better method. We can simply "unpack" the list of values into the appropriate spots using the syntax *iterable
.
.format(key, *value, ...)
And the last value left to fill in would be your total. You can make use of the builtin function sum()
to add all the values in values
together:
.format(key, *value, sum(value))
Now to print the sum of each column, we first need the value of each key in your dict()
. This can be done using a simple list comprehension:
sales = [value for value in d.values()]
Next, we need to get the first value from each list in sales
and add the value. This can be done using a list comprehension and the zip()
builtin function:
totals = [round(sum(l), 1) for l in zip(*sales)]
The round function is used with floats to round them to a certain decimal place. You can change that number to your liking, but I chose one. The last thing left to do is to print the totals of each column. After a bit of experimentation, this should work just fine:
`print("\t\t {}\t {}\t {}".format(*totals))
So the final, finished solution would be:
sales = [value for value in d.values()]
totals = [round(sum(l), 1) for l in zip(*sales)]
for key, value in salesData.items():
print("{} \t {} \t {} \t {} \t Total: {}".format(key, *value, sum(value)))
print("\t\t {}\t {}\t {}".format(*totals))
Answered By - Christian Dean Answer Checked By - Senaida (PHPFixing Volunteer)
0 Comments:
Post a Comment
Note: Only a member of this blog may post a comment.