Search code examples
pythonpython-3.xdictionaryfinance

Calculation between Values and Keys in Dictionarys


I'm trying to perform a calculation between a dictionary value and its respective key.

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

For instance, I would like to discount the cash-flows on the dictionary above. It is important to use the dictionary keys to discount values, so I don´t need to fill blank in between keys.

For each pair in the dictionary, the calculation should be:

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

For any doubt, please feel free to ask. Thanks in advance,


Solution

  • You can either iterate on just the keys, or you can iterate on both:

    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)