Convert array to dictionary

I have an array (w) including binaries (zero and one) that determines whether or not a specific action should be taken on each branch. I want to convert this array to a dictionary in which its values in w can be callable by “(f_bus,t_bus)”. I tried to do that by the following command

bpp= Dict( (branch["f_bus"] , branch["t_bus"]) => w[i] for (i,branch) in case["branch"])    

but I got the following error. Can you please guide me on doing this? Thanks in advance!

ERROR: ArgumentError: invalid index: 4

Seems likely that 4 isn’t a valid index in whatever object w is.

w=[1;1;0;0;1;0]. I want to build a dictionary which its keys are defined by tuple (branch[“f_bus”], branch[“t_bus”]) and its values are w.

Please provide enough code so that we can copy and paste to reproduce.

1 Like

bp is a tuple as follows and consists of (f-bus,t_bus)
(1, 2)
(2, 3)
(1, 4)
(1, 5)
(3, 4)
(4, 5)

w is an aray equal to [1;1;0;1;0;0]. I have a line in my code (i.e., iszero(selc[bp])) which decides based on w[i] values but is callable by "bp"s. Thus I need a dictionary named “selc” in which "bp"s are keys and w[i]s are values.
I will appreciate any help. Thanks in advance!

To get help, you’ll need to provide a self-contained working example.

I think its missing a set of square brackets for the comprehension
Dict([ ((i,i), i) for i in 1:10 ])
Add- except it does work without
Dict( (i,i) => i for i in 1:10) is also ok

possibly the (i,j) iterator

[print(" $i $j ") for (i,j) in 10:-1:1]
Boundserror: Attempt to access 10 at index [2]

[print(" $i $j ") for (i,j) in zip(1:10, 10:-1:1)]
1 10 2 9 ..

quote your code, provide an MWE

Thanks for the response! Following is piece of the code that I was intended to run. I wan to “voltage_angle_difference_tighten_index” be callable by "bp"s. I will appreciate any help!

using PowerModels
using Ipopt
using JuMP


cd("C:\\Users\\username\\.julia\\v0.6\\PowerModels\\test\\data\\matpower")
case=PowerModels.parse_file("case5.m")
pm = build_generic_model(case, QCWRTriPowerModel, PowerModels.post_opf)
result = solve_generic_model(pm, IpoptSolver())
data=case
PowerModels.update_data(data, result["solution"])


aa = getvalue(var(pm, :td))
bpp= Dict( (parse(Int,i),   branch["f_bus"] , branch["t_bus"]) => aa[(branch["f_bus"],branch["t_bus"])] for (i,branch) in data["branch"])
a1 = [(k,v) for (k,v) in bpp]
angdiff1 =  [y[i] for y in a1, i=2]
bus_va = Dict( parse(Int,i) => bus["va"] for (i,bus) in data["bus"])
branch_vad = Dict( (parse(Int,i),   branch["f_bus"] , branch["t_bus"]) => bus_va[branch["f_bus"]] - bus_va[branch["t_bus"]] for (i,branch) in data["branch"])
a2 = [(k,v) for (k,v) in branch_vad]
angdiff2 =  [z[i] for z in a2, i=2]
angdiff=floor.(10^4*(angdiff2-angdiff1))/10.0^4
b2 =  [z[i] for z in a2, i=1]
c2 =  [z[i] for z in b2, i=1]
voltage_angle_difference_tighten = hcat(c2,abs.(angdiff))
voltage_angle_difference_tighten_sort = sortrows(voltage_angle_difference_tighten, by=x->-x[2])
number_of_tightened_incidents=ceil(length(data["branch"])*.2)#   voltage_angle_different_tightened_threshold)
sorted_branches=voltage_angle_difference_tighten_sort[:,1]
voltage_angle_difference_tighten_selected = sorted_branches[1:trunc(Int,number_of_tightened_incidents)]
voltage_angle_difference_tighten_index = zeros(length(data["branch"]),1)
voltage_angle_difference_tighten_index[trunc.(Int,voltage_angle_difference_tighten_selected)]=1

(iszero(voltage_angle_difference_tighten_index[bp])) && (continue)

Thanks for posting this, but I think what Stefan and Tamas were looking for is slightly different - the key aspects of an MWE are that it is both Minimal and Working.

From the code snippet you posted it appears unlikely that it is minimal (there seem to be a lot of rows unrelated to dictionary operations), and it also seems unlikely that it is working (given that it accesses a local file on your computer to construct the case variable).

It’d be really helpful if you could try to narrow your problem down to a small number of lines sufficient to produce the error you’re running into.

1 Like

Thanks for the response!
I narrow the code down to a small number of lines. The line in for loop produce the error because it is not callable with “bp”. “voltage_angle_difference_tighten_index” needs to be converted to a dictionary which can be callable by "bp"s. I will appreciate any help!

using PowerModels
using Ipopt
using JuMP


cd("C:\\Users\\username\\.julia\\v0.6\\PowerModels\\test\\data\\matpower")
case=PowerModels.parse_file("case5.m")
pm = build_generic_model(case, QCWRTriPowerModel, PowerModels.post_opf)
result = solve_generic_model(pm, IpoptSolver())
data=case
PowerModels.update_data(data, result["solution"])

voltage_angle_difference_tighten_index=[1;1;0;0;1;0];
for bp in buspairs
(iszero(voltage_angle_difference_tighten_index[bp])) && (continue)
end

A code which contains lines like this:

will likely not run on any of our machines :wink: I hope you agree…

Thanks for improving your code snippet, but I don’t think we’re quite there yet:

  1. It still appears this isn’t a Minimal example - the dependencies on PowerModels, Ipopt, JuMP seem unnecessary;
  2. It also isn’t Working - I assume the key bit we’re interested in is the last loop, however buspairs is undefined so this doesn’t run.

buspairs definition is in PowerModels.jl and that is why I put using PowerModels. the code needs the PowerModels package to be added. After adding the package my code snippet would work.

Apologies, that wasn’t clear to me - although I get (on v0.7, having added PowerModels):

julia> using PowerModels

julia> buspairs
UndefVarError: buspairs not defined

However it seems your question only relates to indexing dictionaries and standard Arrays, so again it seems unlikely that PowerModels is required to demonstrate your problem.

If your problem is related to voltage_angle_difference_tighten_index[bp] in the loop, ideally you could just create a buspair object using dummy data?

Thanks for the response! Following is exactly what I asked yesterday.
bp is a tuple as follows
(1, 2)
(2, 3)
(1, 4)
(1, 5)
(3, 4)
(4, 5)

w is an aray equal to [1;1;0;1;0;0]. I have a line in my code (i.e., iszero(selc[bp])) which decides based on w[i] values but is callable by "bp"s. Thus I need a dictionary named “selc” in which "bp"s are keys and w[i]s are values.

Okay, this is a lot closer to an MWE, although I’m still not sure what you’re trying to achieve.

Here’s an MWE of what I currently think you’re trying to do:

w=[1;1;0;0;1;0]
buspairs = [(1, 2) (2, 3) (1, 4) (1, 5) (3, 4) (4, 5)]

d  = Dict(buspairs[i] => w[i] for i ∈ 1:6)

d[(1,4)] # returns 0
2 Likes