如何在Python中按降序编写CSV文件,而不使用诸如pandas之类的第三方包?

huangapple go评论57阅读模式
英文:

How to write csv file in descending order in python without using third-party packages such as pandas?

问题

ProductMaster = { 1 : [次要小部件,0.25,250]
2 : [关键小部件,5.00,10]
3 : [完整系统(基本版),500,1]
4 : [完整系统(豪华版),625,1]
}

我通过读取一个 CSV 文件得到了上面的字典(ProductMaster),然后对其进行了一些计算,生成了下面的字典(productReport)。

productReport = { 1 : [687500.0,11000,0.0]
2 : [250000.0,5000,12500.0]
3 : [1500000.0,3000,92500.0]
4 : [0,0,0]
}

字典(productReport)中的列表值的第一个索引表示总收入,我希望使用这个字典按总收入降序输出一个 CSV 文件。

with open(ProductReport_Filename, 'w') as file:

    csvWriter = csv.writer(file)
    
    csvWriter.writerow(["名称","总收入","总销售量","折扣成本"])
    
    productKeys = ProductMaster.keys()
    
    for key,value in productReport.items():
    
        if key in productKeys:
    
            csvWriter.writerow([ProductMaster[key][0], *value])
    
    file.close()

上面的代码生成了以下 CSV 文件:

名称,总收入,总销售量,折扣成本
次要小部件,687500.0,11000,0.0
关键小部件,250000.0,5000,12500.0
完整系统(基本版),1500000.0,3000,92500.0
完整系统(豪华版),0,0,0

但是我希望 CSV 文件按总收入降序排序。因此,输出应该是:

名称,总收入,总销售量,折扣成本
完整系统(基本版),1500000.0,3000,92500.0
次要小部件,687500.0,11000,0.0
关键小部件,250000.0,5000,12500.0
完整系统(豪华版),0,0,0
英文:
ProductMaster = { 1 : [Minor Widget,0.25,250]
                  2 : [Critical Widget,5.00,10]
                  3 : [Complete System (Basic),500,1]
                  4 : [Complete System (Deluxe),625,1]
                }

I got the dictionary (ProductMaster) above by reading a csv file and then I did some calculation to make the dictionary (productReport) below.

productReport = { 1 : [687500.0,11000,0.0]
                  2 : [250000.0,5000,12500.0]
                  3 : [1500000.0,3000,92500.0]
                  4 : [0,0,0]
                }

The first index of the list value in dictionary (productReport) above represents gross revenue, and I want to output a csv file using the dictionary above in descending order in terms of gross revenue.

with open(ProductReport_Filename, 'w') as file:

    csvWriter = csv.writer(file)

    csvWriter.writerow(["Name","GrossRevenue","TotalUnits","DiscountCost"])

    productKeys = ProductMaster.keys()

    for key,value in productReport.items():

        if key in productKeys:

            csvWriter.writerow([ProductMaster[key][0], *value])

    file.close()

The code above gives the csv file below:

Name,GrossRevenue,TotalUnits,DiscountCost
Minor Widget,687500.0,11000,0.0
Critical Widget,250000.0,5000,12500.0
Complete System (Basic),1500000.0,3000,92500.0
Complete System (Deluxe),0,0,0

But I want the csv file to be sorted by gross revenue in descending order. So, the output should be:

Name,GrossRevenue,TotalUnits,DiscountCost
Complete System (Basic),1500000.0,3000,92500.0
Minor Widget,687500.0,11000,0.0
Critical Widget,250000.0,5000,12500.0
Complete System (Deluxe),0,0,0

答案1

得分: 1

只忽略键。 你可能应该将它们存储在一个列表中,而不是一个字典中;带有递增整数键的字典并不是非常有用的。

所以,忽略键,获取值,并对该列表进行排序。

import csv

ProductMaster = { 1 : ['Minor Widget',0.25,250],
                  2 : ['Critical Widget',5.00,10],
                  3 : ['Complete System (Basic)',500,1],
                  4 : ['Complete System (Deluxe)',625,1]
                }

productReport = { 1 : [687500.0,11000,0.0],
                  2 : [250000.0,5000,12500.0],
                  3 : [1500000.0,3000,92500.0],
                  4 : [0,0,0]
                }

# 建立一个合并的列表。

result = [[pm[0]]+pr for pm,pr in zip(ProductMaster.values(), productReport.values())]
result.sort( key=lambda k: -k[1] )

# 写入它。

with open("x.csv", 'w') as file:
    csvWriter = csv.writer(file)
    csvWriter.writerow(["Name","GrossRevenue","TotalUnits","DiscountCost"])
    csvWriter.writerows( result )

输出:

Name,GrossRevenue,TotalUnits,DiscountCost
Complete System (Basic),1500000.0,3000,92500.0
Minor Widget,687500.0,11000,0.0
Critical Widget,250000.0,5000,12500.0
Complete System (Deluxe),0,0,0
英文:

Just ignore the keys. You probably should be storing those in a list instead of a dictionary anyway; dictionaries with incrementing integer keys are not very useful.

So, ignore the keys, grab the values, and sort that list.

import csv

ProductMaster = { 1 : ['Minor Widget',0.25,250],
                  2 : ['Critical Widget',5.00,10],
                  3 : ['Complete System (Basic)',500,1],
                  4 : ['Complete System (Deluxe)',625,1]
                }

productReport = { 1 : [687500.0,11000,0.0],
                  2 : [250000.0,5000,12500.0],
                  3 : [1500000.0,3000,92500.0],
                  4 : [0,0,0]
                }

# Build up a combined list.

result = [[pm[0]]+pr for pm,pr in zip(ProductMaster.values(), productReport.values())]
result.sort( key=lambda k: -k[1] )

# Write it.

with open("x.csv", 'w') as file:
    csvWriter = csv.writer(file)
    csvWriter.writerow(["Name","GrossRevenue","TotalUnits","DiscountCost"])
    csvWriter.writerows( result )

Output:

Name,GrossRevenue,TotalUnits,DiscountCost
Complete System (Basic),1500000.0,3000,92500.0
Minor Widget,687500.0,11000,0.0
Critical Widget,250000.0,5000,12500.0
Complete System (Deluxe),0,0,0

答案2

得分: 1

你可以创建一个元组列表,然后按总收入降序对数据进行排序。

import csv

# 定义字典
ProductMaster = {1: ['小部件', 0.25, 250],
                2: ['关键小部件', 5.00, 10],
                3: ['完整系统(基本)', 500, 1],
                4: ['完整系统(豪华)', 625, 1]
                }

productReport = {1: [687500.0, 11000, 0.0],
                2: [250000.0, 5000, 12500.0],
                3: [1500000.0, 3000, 92500.0],
                4: [0, 0, 0]
                }

# 创建一个元组列表来表示数据
data = []
for key, value in productReport.items():
    data.append((key, ProductMaster[key][0], value[0], value[1], value[2]))

# 按总收入对数据进行排序
data_sorted = sorted(data, key=lambda x: x[2], reverse=True)

# 将数据写入CSV文件
with open('product_sales_report.csv', 'w', newline='') as csvfile:
    writer = csv.writer(csvfile)
    writer.writerow(['产品ID', '产品名称', '总收入', '总单位', '折扣成本'])
    for row in data_sorted:
        writer.writerow(row)
英文:

You can create a list of tuples, then sort the data by gross revenue in descending order.

import csv

# Define the dictionaries
ProductMaster = { 1 : ['Minor Widget',0.25,250],
                  2 : ['Critical Widget',5.00,10],
                  3 : ['Complete System (Basic)',500,1],
                  4 : ['Complete System (Deluxe)',625,1]
                }

productReport = { 1 : [687500.0,11000,0.0],
                  2 : [250000.0,5000,12500.0],
                  3 : [1500000.0,3000,92500.0],
                  4 : [0,0,0]
                }

# Create a list of tuples to represent the data
data = []
for key, value in productReport.items():
    data.append((key, ProductMaster[key][0], value[0], value[1], value[2]))

# Sort the data by gross revenue
data_sorted = sorted(data, key=lambda x: x[2], reverse=True)

# Write the data to a CSV file
with open('product_sales_report.csv', 'w', newline='') as csvfile:
    writer = csv.writer(csvfile)
    writer.writerow(['Product ID', 'Product Name', 'Gross Revenue', 'Total Units', 'Discount Cost'])
    for row in data_sorted:
        writer.writerow(row)

答案3

得分: 1

根据https://stackoverflow.com/questions/613183/how-do-i-sort-a-dictionary-by-value,您现在可以对字典进行排序。

您还可以创建一个新字典,对其进行排序和操作,但如果您想对原始字典进行排序,请使用以下行:

productReport = {k: v for k, v in sorted(productReport.items(), key=lambda item: item[1], reverse=True)}

reverse参数用于返回降序排序。

完整的程序如下,以及输出:

import csv

ProductMaster = { 1 : ["Minor Widget",0.25,250],
                  2 : ["Critical Widget",5.00,10],
                  3 : ["Complete System (Basic)",500,1],
                  4 : ["Complete System (Deluxe)",625,1]
                }

productReport = { 1 : [687500.0,11000,0.0],
                  2 : [250000.0,5000,12500.0],
                  3 : [1500000.0,3000,92500.0],
                  4 : [0,0,0]
                }

with open("c:/users/queen/documents/testexcel.csv", 'w') as file:

    csvWriter = csv.writer(file)

    csvWriter.writerow(["Name","GrossRevenue","TotalUnits","DiscountCost"])

    productKeys = ProductMaster.keys()

    productReport = {k: v for k, v in sorted(productReport.items(), key=lambda item: item[1], reverse=True)}

    for key,value in productReport.items():

        if key in productKeys:

            csvWriter.writerow([ProductMaster[key][0], *value])

    file.close()

如何在Python中按降序编写CSV文件,而不使用诸如pandas之类的第三方包?

英文:

According to https://stackoverflow.com/questions/613183/how-do-i-sort-a-dictionary-by-value, you may now sort dictionaries.

You can also create a new dictionary, sort and work with that, but if you want to sort the original, use the line

productReport = {k: v for k, v in sorted(productReport.items(), key=lambda item: item[1], reverse=True)}

The reverse parameter is used to return a descending order.

The complete program is below, along with an output:

import csv

ProductMaster = { 1 : ["Minor Widget",0.25,250],
                  2 : ["Critical Widget",5.00,10],
                  3 : ["Complete System (Basic)",500,1],
                  4 : ["Complete System (Deluxe)",625,1]
                }

productReport = { 1 : [687500.0,11000,0.0],
                  2 : [250000.0,5000,12500.0],
                  3 : [1500000.0,3000,92500.0],
                  4 : [0,0,0]
                }

with open("c:/users/queen/documents/testexcel.csv", 'w') as file:

    csvWriter = csv.writer(file)

    csvWriter.writerow(["Name","GrossRevenue","TotalUnits","DiscountCost"])

    productKeys = ProductMaster.keys()

    # Use 
    productReport = {k: v for k, v in sorted(productReport.items(), key=lambda item: item[1], reverse=True)}

    for key,value in productReport.items():

        if key in productKeys:

            csvWriter.writerow([ProductMaster[key][0], *value])

    file.close()

如何在Python中按降序编写CSV文件,而不使用诸如pandas之类的第三方包?

答案4

得分: 0

让我们尝试在不重写代码的情况下做一些事情。

其中一个解决方案是按照productReport字典的键列表的第一个项目(也就是GrossRevenue)对其进行排序。

import operator
productReport = {1: [687500.0, 11000, 0.0],
                 2: [250000.0, 5000, 12500.0],
                 3: [1500000.0, 3000, 92500.0],
                 4: [0, 0, 0]
                }

print(dict(sorted(productReport.items(), key=operator.itemgetter(1), reverse=True)))

字典将按键的列表进行排序。同时,列表会根据内部的第一个元素自动排序。我们添加了reverse参数,以便按降序排序。

输出将如下所示:

{3: [1500000.0, 3000, 92500.0], 
 1: [687500.0, 11000, 0.0], 
 2: [250000.0, 5000, 12500.0], 
 4: [0, 0, 0]
}

因此,我们应该添加一行并更改变量:

...

productKeys = ProductMaster.keys()

sorted_productReport = dict(sorted(
                            productReport.items(), 
                            key=operator.itemgetter(1), 
                            reverse=True))

for key,value in sorted_productReport.items():

    if key in productKeys:

        csvWriter.writerow([ProductMaster[key][0], *value])
英文:

Let's try to do something without code rewriting.

One of solutions is to sort productReport dictionary by first item of key's list (in other words, according GrossRevenue)

import operator
productReport = { 1 : [687500.0,11000,0.0],
                  2 : [250000.0,5000,12500.0],
                  3 : [1500000.0,3000,92500.0],
                  4 : [0,0,0]
                }

print(dict(sorted(productReport.items(), key=operator.itemgetter(1), reverse=True)))

The dictionary will be sorted by the keys' lists. Meanwhile, lists are automatically sorted according to the first inner element. We add reverse argument to make them be sorted in descending order.

The output will look like

{ 3: [1500000.0, 3000, 92500.0], 
  1: [687500.0, 11000, 0.0], 
  2: [250000.0, 5000, 12500.0], 
  4: [0, 0, 0]
}

So, we should add one row and change the variable

    ...

    productKeys = ProductMaster.keys()
    
    sorted_productReport = dict(sorted(
                                productReport.items(), 
                                key=operator.itemgetter(1), 
                                reverse=True))

    for key,value in sorted_productReport.items():

        if key in productKeys:

            csvWriter.writerow([ProductMaster[key][0], *value])

答案5

得分: 0

内置的sorted方法可用于对字典进行排序。https://docs.python.org/3/library/functions.html#sorted

使用一个可迭代的字典项(items),其中key是一个回调函数,根据第一个列表项进行排序,reverse标志用于降序排序。

sorted的输出始终是一个列表。

[(3, [1500000.0, 3000, 92500.0]), (1, [687500.0, 11000, 0.0]), (2, [250000.0, 5000, 12500.0]), (4, [0, 0, 0])]

你可以轻松地将其转换为字典,使用dict()。

dict(sorted(productReport.items(), key = lambda x:x[1][0],reverse=True))

{3: [1500000.0, 3000, 92500.0], 1: [687500.0, 11000, 0.0], 2: [250000.0, 5000, 12500.0], 4: [0, 0, 0]}

英文:

The builtin sorted method can be used to sort a dictionary. https://docs.python.org/3/library/functions.html#sorted

sorted(productReport.items(), key = lambda x:x[1][0],reverse=True)

Passing an iterable dictionary items, with key being a callback function which sorts using the first list item and reverse flag for sorting with a descending order.

The output of sorted is always a list.

[(3, [1500000.0, 3000, 92500.0]), (1, [687500.0, 11000, 0.0]), (2, [250000.0, 5000, 12500.0]), (4, [0, 0, 0])]

You can easily convert it to dictionary with dict()

dict(sorted(productReport.items(), key = lambda x:x[1][0],reverse=True))
>>> {3: [1500000.0, 3000, 92500.0], 1: [687500.0, 11000, 0.0], 2: [250000.0, 5000, 12500.0], 4: [0, 0, 0]}

huangapple
  • 本文由 发表于 2023年2月19日 02:57:06
  • 转载请务必保留本文链接:https://go.coder-hub.com/75495676.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定