簡體   English   中英

如何從具有特定要求的字典中打印鍵和值

[英]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()

當我以當前狀態運行程序時,它會給我以下輸出:

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

但是,我需要它看起來像這樣:

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**

干凈、有條理、有標簽、完美對齊。 我不知道如何以干凈的方式從字典中提取數據。 此外,我還必須添加巧克力等的總數以及第 1、第 2 和第 3 列。 介紹很重要。 這不僅僅是“我如何輸出數據”,而是“我如何以干凈的呈現方式輸出數據”。 我正在考慮使用嵌套的 for 循環,或者可能是帶有 for 循環的東西。 但是 for 循環的去向,或者我如何使用它來干凈地打印出字典數據,我希望它看起來像什么,這超出了我的范圍。 我已經查看了其他問題,但沒有什么能比得上來自字典的數據的制表、組織和打印細節。 我也嘗試過經常引用的“for key, val in X.items():”,但這對我沒有用。 我什至不知道從哪里開始該功能及其令人難以置信的混亂。 我會把它放在哪里? 我該如何命名它? 我會從那里去哪里? 更不用說我有要添加的列和要添加的行。 這是一個非常具體的問題。 謝謝你。

您可以使用python的字符串格式來創建常規外觀。

有一個很好的網站專門用於python格式化: https : //pyformat.info

表格行的格式如下所示:

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

然后,您可以填寫以下字段:

>>> 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'

要將這些字段從字典中拉出:

>>> 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

Python具有出色的迷你語言,專門用於字符串格式化。 這是應該使用的。

您知道您希望自己的格式是

flavor sell1 sell2 sell3 Total: total sells

等於以下字符串格式:

"{} \\t {} \\t {} \\t {} \\t Total: {}"

因此,既然您知道格式了,那么下一步就是將這種格式應用於字典中的每個key, value對。 使用for循環遍歷每個key, value對。

for key, value in dictionary.items():
    print("{} \t {} \t {} \t {} \t Total: {}".format(...))

剩下要做的最后一件事是填補空白。 您知道dict()中的key是風味,因此format()的第一個參數將是key變量:

.format(key, ...)

接下來,您需要key的三個值。 我們可以從value索引每個value

.format(key, value[0], value[1], value[2], ...)

Bu有點冗長,Python有更好的方法。 我們可以簡單地使用*iterable語法*iterable值列表“解包”到適當的位置。

.format(key, *value, ...)

最后剩下的值就是您的總數。 您可以使用內置函數的sum()中添加的所有值values一起:

.format(key, *value, sum(value))

現在要打印每列的總和,我們首先需要您的dict()中每個鍵的值。 這可以通過簡單的列表理解來完成:

sales = [value for value in d.values()]

接下來,我們需要從sales每個列表中獲取第一個值並添加該值。 這可以使用列表推導和zip()內置函數來完成:

totals = [round(sum(l), 1) for l in zip(*sales)]

舍入功能與浮點數一起使用,可以將它們舍入到某個小數位。 您可以根據自己的喜好更改該數字,但我選擇了一個。 剩下要做的最后一件事是打印每列的總計。 經過一些試驗,這應該可以正常工作:

`print("\t\t {}\t {}\t {}".format(*totals))

因此,最終的最終解決方案將是:

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))

請嘗試以下操作:

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)))

輸出:

>>> 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
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)))

在def main()內部輸入:您將獲得所需的輸出。

您可以使用庫outputformat來幫助顯示字典。

pip install outputformat

然后嘗試以下操作:


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)

這應該會給你以下結果:

╭────────────────────╮
│ 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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM