# Gurobi how to get variable coefficients in constraints

**URL:** <https://discourse.julialang.org/t/gurobi-how-to-get-variable-coefficients-in-constraints/54150>\
**Category:** Optimization (Mathematical)\
**Tags:** jump\
**Created:** [January 29, 2021, 12:16am UTC](https://discourse.julialang.org/t/gurobi-how-to-get-variable-coefficients-in-constraints/54150 "2021-01-29T00:16:58Z")\
**Posts on this page:** 1\
**Showing post:** 5

<div class="post-metadata">

**Author:** ![rezabayani](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/rezabayani/32/25954_2.png) [@rezabayani](https://discourse.julialang.org/u/rezabayani)\
**Post date:** [January 29, 2021, 3:31am UTC](https://discourse.julialang.org/t/gurobi-how-to-get-variable-coefficients-in-constraints/54150/5 "2021-01-29T03:31:16Z")

</div>

Okay here is an interesting one. Your method returns an error if the constraint does not contain that variable. For example:

```julia
cc[1,1] # segment_power[1,1] : p_g_seg[1,1,1] + p_g_seg[1,2,1] + p_g_seg[1,3,1] - p_g[1,1] == 0.0
con = constraint_object(cc[1,1])
con.func.terms
#=
OrderedCollections.OrderedDict{VariableRef,Float64} with 4 entries:
  p_g_seg[1,1,1] => 1.0
  p_g_seg[1,2,1] => 1.0
  p_g_seg[1,3,1] => 1.0
  p_g[1,1] => -1.0
=#
haskey(con.func.terms, "p_g[1,1]") #false
haskey(con.func.terms, p_g[1,1]) #false
collect(keys(con.func.terms))
#=
4-element Array{VariableRef,1}:
 p_g_seg[1,1,1]
 p_g_seg[1,2,1]
 p_g_seg[1,3,1]
 p_g[1,1]
=#
p_g[1,1] in collect(keys(con.func.terms)) #false
typeof(collect(keys(con.func.terms))[4]) #VariableRef
typeof(p_g[1,1]) #VariableRef
con.func.terms[p_g[1,1]] # -1.00
con.func.terms[p_g[1,2]] #KeyError: key p_g[1,2] not found

```

Besides your suggestion, I also found [How do I extract the coefficients and RHS's of all constraints in a JuMP linear program? (Need for KKT) - #4 by odow](https://discourse.julialang.org/t/how-do-i-extract-the-coefficients-and-rhss-of-all-constraints-in-a-jump-linear-program-need-for-kkt/38525/4) and it suggested using some NLP package that returns “A” matrix. However, it is quite a challenge to figure out the ordering of that A matrix in large cases. Do you have any idea how to get around this issue?

---

_[View the full topic](https://discourse.julialang.org/t/gurobi-how-to-get-variable-coefficients-in-constraints/54150)._
