简体   繁体   中英

KeyError: 0 Python

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])

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.

The expression P is not the same as p . In your code, the first is a range, the second is an integer from that range.

So, the expression RP[P,T] is wrong in two ways: it uses the wrong subscripts, and combines them the wrong way (as another answer points out).

I think you want RP[p][t] instead.

keyerror: 0 generally means that you are trying to access the value stored in a non-existing key 0 in a dictionary.

In your code it happens because, being

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

you get

print(T)
 range(0, 14)

so its first element is 0 ,
and when you run this

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])

you have that the first value got by t is 0 , and then you pass that t to dictionary demand , which has no key 0 , and there is where I guess keyerror: 0 is raised.

Also, as pointed out by other questions, you should notice that

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.

To help you fix your code it might be useful to know how RP is defined.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM