'How to print keys and values from dictionary with specific requirements

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 1:[1]

You can use python's string formatting to create a regular appearance.

There's a nice website just to do with python formatting: https://pyformat.info

The format of the table row will look something like:

>>> row = '{flavour}\t{sales[0]}\t{sales[1]}\t{sales[2]}\tTotal: {total}'

Then you can fill in the fields:

>>> row.format(flavour='chocolate',
...            sales=[10225.25, 9025.0, 9505.0],
...            total=sum([10225.25, 9025.0, 9505.0]))
'chocolate    10225.25   9025.0      9505.0      Total: 28755.25'

To pull these fields out of the dictionary:

>>> for flavour, sales in salesData.items():
...     print(row.format(flavour=flavour,
...                      sales=sales,
...                      total=sum(sales)))
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

Solution 2:[2]

Try the following:

def format_data(data):
    for item in data:
        print('{:15} {:15} {:15} {:15} {:10} Total:{:5}'.format(
            item, data[item][0], data[item][1], data[item][2], '',
            sum(data[item])))
    print('{:15} {:15} {:15} {:15}'.format('',
        sum(data[item][0] for item in data),
        sum(data[item][1] for item in data),
        sum(data[item][2] for item in data)))

Output:

>>> data = {'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]}

>>> format_data(data)
rocky road               6700.1         5012.45          6011.0            Total:17723.55
strawberry              9285.15          8276.1          8705.0            Total:26266.25
vanilla                  8580.0         7201.25          8900.0            Total:24681.25
cookie dough            7901.25          4267.0          7056.5            Total:19224.75
chocolate              10225.25          9025.0          9505.0            Total:28755.25
                       42691.75         33781.8         40177.5

Solution 3:[3]

for key, value in salesData.items():
    print("{} \t {} \t {} \t {} \t Total: {}".format(key, *value, sum(value)))
print("\t", "{} \t {} \t {} \t {} \t".format('',
sum(salesData[value][0] for value in salesData),
sum(salesData[value][1] for value in salesData),
sum(salesData[value][2] for value in salesData)))

Enter inside the def main(): and you will get the desired output.

Solution 4:[4]

You could use the library outputformat to help displaying dictionaries.

pip install outputformat

Then try the following:


import outputformat as ouf

d = {'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]}

ouf.showdict(d, title="Ice cream flavours", style="box", precision=2)

This should give you the following result:

??????????????????????
? Ice cream flavours ?
??????????????????????
? chocolate...: 10225.25, 9025.00, 9505.00
? strawberry..: 9285.15, 8276.10, 8705.00
? cookie dough: 7901.25, 4267.00, 7056.50
? rocky road..: 6700.10, 5012.45, 6011.00
? vanilla.....: 8580.00, 7201.25, 8900.00

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2
Solution 3 ice cream
Solution 4 Delestro