nested for loop dictionary store values python nsepy

175 Views Asked by At
startdate = datetime.date(2018,1,1)
expirydate = datetime.date(2018,1,4)
data = dict()

for x in range(0,3):
    for y in range(1,8):
        data [y] = get_history(symbol="BANKNIFTY",
                        start= startdate,
                        end= startdate,
                        index=True,
                        option_type='CE',
                        strike_price= 27000,
                        expiry_date=expirydate)
        startdate += datetime.timedelta(days=1)

    expirydate += datetime.timedelta(days=7)

The loop works well but only gives me last set of values i.e. when x = 3. Rest all previous values gets overridden.

1

There are 1 best solutions below

0
busybear On

You are going to have to differentiate the different y values from the ones in the previous loops of x values. For instance you can set data[(x, y)] instead of data[y]. To avoid adding empty values, just add the conditional to check for a value before setting it to your dictionary:

for x in range(0,3):
    for y in range(1,8):
        val = get_history(symbol="BANKNIFTY",
                        start= startdate,
                        end= startdate,
                        index=True,
                        option_type='CE',
                        strike_price= 27000,
                        expiry_date=expirydate)
        if val:
            data[(x, y)] = val
        ...