字典中值和键之间的计算

Calculation between Values and Keys in Dictionarys

我正在尝试在字典值及其相应键之间执行计算。

dict_cashflows = {0:-10000, 1: 500, 2: 1500, 10: 10000} rate=0.06

例如,我想对上面字典中的现金流进行贴现。使用字典键来打折值很重要,所以我不需要在键之间填空。

对于字典中的每一对,计算应该是:

value/((1+rate)**key)

如有任何疑问,请随时提问。 提前致谢,

您可以只对键进行迭代,也可以对两者进行迭代:

dict_cashflows = {0:-10000, 1: 500, 2: 1500, 10: 10000}
rate=0.06
cashflow = {k : dict_cashflows[k] / (1.+rate)**k for k in dict_cashflows.keys()} #building a new dict from iterating over keys
print(cashflow)
cashflow2 = {k : v / (1.+rate)**k for k,v in dict_cashflows.items()} #building a new dict while iterating on both
print(cashflow2)

所以,这就是我找到的方法:

dict_cashflows = {0:-10000, 1: 500, 2: 1500, 10: 10000}

   `def NPV_dict(dictcfs,rate=0.06):
    npv=0.0
    periods=list(dictcfs.keys())
    cfs=list(dictcfs.values())
    for i in range(len(dict_cashflows)):
        calc=cfs[i]/((1+rate)**(periods[i]))
        npv+=calc    
    return npv`