【发布时间】:2021-07-15 12:17:46
【问题描述】:
我有以下 CSV,它是 Python 中的字典输入。在这种情况下是 Test.csv。
Cust_Id, No_of_purchases, Amount
xxx0001, 2000,3000
xxx0002, 30 ,400
xxx0002, 20,500
下面的代码读取它并将字典键输出为“Customer_ID”,其余的输出为值。
with open('Test.csv', mode='r') as csv_input:
reader = [[x.strip() for x in rows.split(",")] for rows in csv_input.readlines()]
(customer_, *Purchases_amount), *row_values = reader
dict_ = {}
for each_row in row_values:
key, *values = each_row
dict_from_csv[key] = {key: value for key, value in zip(Purchases_amount, values)}
打印dict_from_csv 的结果如下所示,加上另外两行。
{'xxx0001': {'No_of_purchases': '2000',
'Amount': '3000'}, .....
问题是:如果金额大于 1000,我如何应用 5% 的折扣,否则字典中“金额”值的折扣为 0?关键是 Cust_Id。我有以下函数来计算折扣。如何将其应用于字典中的“金额”值?
def givediscount (value):
dis= 0.05*value
nodiscount = 0
if value > 1000:
dis = nodiscount
break
nodiscount+=1
return dis
【问题讨论】:
-
if value < value这个函数是怎么工作的? -
感谢您注意到这一点。已更正。
-
仍然无法工作。
-
@Hummer 问题是您曾经(现在仍然)比较相同的变量
value -
对@Alex。希望会更好。
标签: python csv dictionary