Python 如何根据特定要求打印字典中的键和值

Python 如何根据特定要求打印字典中的键和值,python,dictionary,format,output,Python,Dictionary,Format,Output,当我在当前状态下运行程序时,它将提供以下输出: 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 a

当我在当前状态下运行程序时,它将提供以下输出:

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]}
整洁、有序、标签式、完美对齐。我不知道如何以干净的方式从字典中提取数据。此外,我还要加上巧克力等的总数以及第一、第二和第三列。演讲很重要。这不仅仅是一个“如何输出数据”,而是“如何以干净的表示输出数据”。我正在考虑使用嵌套for循环,或者使用带有for循环的东西。但是for循环的去向,或者我如何使用它来清晰地打印字典数据,以及我希望它看起来是什么样子,这些都是我无法理解的。我已经研究了其他问题,但是没有任何一个问题能与来自字典的数据的制表、组织和打印细节的级别接近。我也尝试过经常引用的“X.items()中的for key,val:”,但这对我来说不起作用。我甚至不知道从哪里开始使用这个函数,它令人难以置信地困惑。我该把它放在哪里?我该怎么命名呢?从那里我会去哪里?更不用说我要添加列和行了。这是一个非常具体的问题。多谢各位

您可以使用python创建常规外观

有一个很好的网站专门处理python格式:

表格行的格式如下所示:

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**
然后您可以填写以下字段:

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

Python有一种专门用于字符串格式化的优秀迷你语言。这是应该使用的

你知道你希望你的格式是

flavor sell1 sell2 sell3总计:总计销售额

这将等同于以下字符串格式:

“{}\t{}\t{}\t{}\t{}\t总计:{}”

现在您已经知道了格式,下一步是将此格式应用于字典中的每个
键、值对。使用for循环迭代每个
键、值对

>>> 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
剩下要做的最后一件事就是填空。您知道
dict()
中的
key
s是风格,因此
format()
的第一个参数是
key
变量:

.format(键…)

接下来,您需要
键中的三个值,即值。我们可以从
中索引每个值:

.format(键、值[0]、值[1]、值[2]、…)

但是这有点冗长,Python有一个更好的方法。我们可以简单地使用语法
*iterable
将值列表“解压”到适当的位置

.format(键,*值,…)

最后一个要填写的值就是你的总数。您可以使用内置函数
sum()
值中的所有值添加到一起:

.format(键、*值、和(值))

现在要打印每列的总和,我们首先需要
dict()
中每个键的值。这可以通过简单的列表理解来完成:

for key, value in dictionary.items():
    print("{} \t {} \t {} \t {} \t Total: {}".format(...))
接下来,我们需要从
sales
中的每个列表中获取第一个值并添加该值。这可以使用列表理解和
zip()
内置函数来完成:

sales = [value for value in d.values()]
round函数与float一起使用,将它们四舍五入到某个小数位。你可以根据自己的喜好更改号码,但我选择了一个。剩下要做的最后一件事是打印每列的总数。经过一点试验后,这应该可以正常工作:

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

在def main()内输入:您将获得所需的输出

我不知道那里发生了什么…peter的回答没有提到添加列的问题…而且,您的代码非常优秀,工作非常好,只是没有添加列。我在考虑(也许你可以在这里帮助我)在0处初始化三列(col1、col2和col3),然后+=它们的值[0][1]和[2],然后打印
print(“\t\t”,col1,“\t”,col2,“\t”,col3)
,但是它不工作:它不打印列的总和。只是其中一种口味。是的。我从你的建议中得到了我想要的结果,我顺利地运行了它;但是,它只缺少三个数字:
42691.7533781.840177.5
。也就是说,我仍然不知道如何将每个键的[0]值相加成一个数字,打印在相应列的下方(对[1]值和[2]值重复)。好了@ice cream,我的分站结束了。如果对你有好处就告诉我。嘿,谢谢你,彼得。谢谢。不过,有几个问题:for循环到哪里去了?它是否在
salesData=readData('icecream.txt')
之后的
def main():
函数中?此外,如果可能的话,我希望避免我手动将数据带入程序。您知道,目标是将名为
icecream.txt
(包含字典信息)的文件中的信息直接输出为类似excel的格式。我应该能够用,比如说,
candy.txt
替换
icecream.txt
,并以相同的格式输出,而无需手动将所有数据转移到核心程序中。
printReport
看起来是一个很好的循环位置。另外,要将数据的文件名传递到脚本中,请参见,或者更好,谢谢!这对我有用。但是,我缺少一件事:如何输出每一列下面的列的总和。任何帮助都将不胜感激。我得到一个错误,在“d.values()”中说“d”没有定义…为什么?谢谢我不认为这是OP想要的。他的所有行都在前面对齐。输出是正确的,所以这很好!但我最大的抱怨是你的大笑话。也许那些
>>> 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)))