【问题标题】:How to apply a function on a dictionary value in Python?如何在 Python 中的字典值上应用函数?
【发布时间】: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


【解决方案1】:

您可以像这样在字典上应用函数:

def give_discount(row):
    amount = row.get("Amount", 0)
    if amount > 1000:
        row["discounted_amount"] = 0.95 * amount
    else:
        row["discounted_amount"] = amount
    return row

dict_from_csv = {k: give_discount(row) for k, row in dict_from_csv.items()}
    

【讨论】:

  • discounted_amount 来自哪里?
  • @LeiYang 是每个子词典中的一个新字段。它保留了原始数量
【解决方案2】:

给定的折扣函数似乎是错误的。根据您的描述,这应该可以工作

def give_discount(amount):
    if amount > 1000:
        return amount * 0.95
    return amount

您可以遍历字典中的元素并调用该函数

for i in dict_from_csv.keys():
    dict_from_csv[i]['Amount'] = give_discount(dict_from_csv[i]['Amount'])

【讨论】:

    猜你喜欢
    • 2019-12-05
    • 2016-01-01
    • 1970-01-01
    • 2020-01-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-03-21
    • 2022-11-02
    相关资源
    最近更新 更多