KeyError: 0 Python

Fino picture Fino · Oct 27, 2017 · Viewed 12.1k times · Source

Hi I'm still pretty new in python and would like to know why this line:

    RP[p][t] = demand[p][t] / fillingrate[p]

is leading to the error: KeyError: 0

it follows the relevant part of the code. Is it just a mistake of notation or what's the best way to solve it?

    productname = ('milk', 'yoghurt', 'buttermilk')
    fillingrate = (1.5, 1.0, 2.0)

    day = (1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14)

    demand = [
    (5, 4, 3, 3, 4, 9, 13, 5, 4, 4, 3, 5, 10, 12),
    (3, 5, 3, 5, 5, 4,  3, 4, 3, 4, 3, 4,  5,  5),
    (3, 3, 5, 4, 4, 5,  4, 3, 4, 3, 4, 5,  4,  5)
    ]

    T = range (len(day))
    P = range (len(productname))


    for p in P:
       for t in T:
            RP[P,T] = model.addVar (lb = 0, vtype = GRB.CONTINUOUS,
            name = 'Regular Production[' + str(p) + ',' + str(t) + ']')
            print(demand[p][t])
            print(fillingrate[p])
            RP[p][t] = demand[p][t] / fillingrate[p]
            print(RP[p][t])

Answer

Ignacio Vazquez-Abrams picture Ignacio Vazquez-Abrams · Oct 27, 2017

Indexing by [x, y] is absolutely not the same as indexing by [x][y]. The former results in a single dimension indexed using a tuple, whereas the latter results in a ragged 2-D array.

You will need to create a new object at the index [x] containing the values you want.