Gurobi与Python新手求助:代码运行出现KeyError: 0错误排查
KeyError: 0 in Your Gurobi-Python Code Hey there! Let's break down why you're hitting that KeyError: 0 on the final line of your code, and how to fix it quickly.
The Root Cause
Looking at your variable definition:
Z = {(a,b): m.addVar() for a in A for b in B}
You’ve created Z as a dictionary where each key is a tuple (a, b) (like (0,0), (0,1), etc.). But in your objective function, you’re trying to access it like a 2D list:
Z[a][b]
This code first tries to fetch Z[a]—meaning it looks for a key that’s just the integer a (like 0 when a=0). Since your dictionary only has tuple keys, there’s no entry for 0, hence the KeyError.
The Fix
You have two simple options to resolve this:
Use the correct dictionary key syntax
ReplaceZ[a][b]withZ[a, b](orZ[(a, b)]—Python lets you omit parentheses for tuple keys):m.setObjective(quicksum((PC+X[a]+Y[a][b])*Z[a, b] for a in A for b in B), GRB.MINIMIZE)Define Z as a 2D list instead
If you prefer theZ[a][b]syntax, redefine your variable as a nested list instead of a dictionary:# Replace the original Z definition with this Z = [[m.addVar() for b in B] for a in A]Then your original objective function line will work exactly as written.
Either approach will eliminate the KeyError and let your model compile correctly.
内容的提问来源于stack exchange,提问作者Ruby Pa

