Skip to content Skip to sidebar Skip to footer

How To Iterate Nested Lists With Another List To Create A Dictionary Of Lists Python

I'm using Mibian module to calculate call options. I have a list of three nested lists. Each nested list represent strike prices. Each nested list has their own respective days lef

Solution 1:

I think this does what you want. Please note, most of this is trying to simulate your environment - you only care about the last couple of lines.

That said, a data structure indexed by sequential numbers shouldn't be a dict, it should be a list. ;-)

Magic_numbers = [
    100.01095590221843,
    95.013694877773034,
    90.016433853327641,
    85.019172828882233,
    80.021911804436854,
    75.024650779991447,
    70.027389755546068,
    68.028485345767905,
    66.029580935989742,
    64.030676526211579,
    62.03177211643343,
    60.032867706655267,
    43.042180223540925,
    22.05368392087027,
    19.055327306203068,
    90.016433853327641,
    80.021911804436854,
    70.027389755546068,
    60.032867706655267,
]

Magic_index = 0

def mb(details, volatility):
    class C:
        def __init__(self, n):
            self.callPrice = n

    global Magic_index
    result = C(Magic_numbers[Magic_index])
    Magic_index += 1
    return result

mb.BS = mb

strike_prices = [
    [20, 25, 30, 35, 40, 45],
    [50, 52, 54, 56, 58, 60, 77, 98, 101],
    [30, 40, 50, 60]
]

days_left = [5, 12, 30]

data99 = {}  # This is silly. A dict indexed by sequential numbers should be a list.

for i, (days, prices) in enumerate(zip(days_left, strike_prices)):
    data99[i] = [mb.BS([120, price, 1, days], 10).callPrice for price in prices]

import pprint
pprint.pprint(data99)

The output looks like this:

{0: [100.01095590221843,
     95.01369487777303,
     90.01643385332764,
     85.01917282888223,
     80.02191180443685,
     75.02465077999145],
 1: [70.02738975554607,
     68.0284853457679,
     66.02958093598974,
     64.03067652621158,
     62.03177211643343,
     60.03286770665527,
     43.042180223540925,
     22.05368392087027,
     19.05532730620307],
 2: [90.01643385332764,
     80.02191180443685,
     70.02738975554607,
     60.03286770665527]}

Solution 2:

I think the answer might be as simple as:

for x, (days_left, my_list) in enumerate(new_list):
     data5[x] = option5 = []
     for days_left, my_list in new_list:
          c = mb.BS([120, my_list, 1, days_left ], 10)
                    option5.append(c.callPrice)

Because the output of enumerate will be in the form (i, x), where in this case x is a tuple (i.e. (i, (x, y))).


Post a Comment for "How To Iterate Nested Lists With Another List To Create A Dictionary Of Lists Python"