You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Gurobi与Python新手求助:代码运行出现KeyError: 0错误排查

Fixing the 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:

  1. Use the correct dictionary key syntax
    Replace Z[a][b] with Z[a, b] (or Z[(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)
    
  2. Define Z as a 2D list instead
    If you prefer the Z[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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.07 07:12:41