pythondictionaryquantlib-swig

Extract value from a dictionary using key that is a list


I have a the following programme:

import QuantLib as ql

deposits = {ql.Period(1,ql.Weeks): 0.0023, 
            ql.Period(1,ql.Months): 0.0032,
            ql.Period(3,ql.Months): 0.0045,
            ql.Period(6,ql.Months): 0.0056}

for n, unit in [(1,ql.Weeks),(1,ql.Months),(3,ql.Months),(6,ql.Months)]:
    print deposits([n,unit])

What I expect this programme to do is: it loops through the dictionary keys, which comprises an embedded list of a 'number' (i.e. 1,1,3,6) and 'unit' (i.e. weeks and months), and extracts the correct value (or rate). Currently I get an error with the line print deposits([n,unit]).

Here is the error I get:

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "C:\Anaconda2\lib\site-packages\spyderlib\widgets\externalshell\sitecustomize.py", line 699, in runfile
    execfile(filename, namespace)
  File "C:\Anaconda2\lib\site-packages\spyderlib\widgets\externalshell\sitecustomize.py", line 74, in execfile
    exec(compile(scripttext, filename, 'exec'), glob, loc)
  File "TestFunction.py", line 16, in <module>
    print deposits([n,unit])   
TypeError: 'dict' object is not callable

The name of my file is TestFunction.py

I know a way round this issue, which is where I convert the dictionary into two lists as follows:

depoMaturities = [ql.Period(1,ql.Weeks), 
                  ql.Period(1,ql.Months),
                  ql.Period(3,ql.Months),
                  ql.Period(6,ql.Months)]

depoRates = [0.0023, 
             0.0032,
             0.0045,
             0.0056]

But then it does not look as tidy or as sophisticated. I'd be really grateful for your advice.


Solution

  • deposits is a dictionary with keys and values. The reference of a dictionary is

     value = mydict[key]
    

    Thus given n and unit you get that ql.Period(n, unit) returns a type of <class 'QuantLib.QuantLib.Period'>. The result of ql.period(1, ql.Weekly) for example would be 1W.

    It would appear that if it is converted to a string, then it would be usable as a key.

    deposits = {str(ql.Period(1,ql.Weeks)): 0.0023, 
                str(ql.Period(1,ql.Months)): 0.0032,
                str(ql.Period(3,ql.Months)): 0.0045,
                str(ql.Period(6,ql.Months)): 0.0056}
    
    value = deposits[str(ql.Period(n, unit))]
    print value