I have a set of years like that:
years = [2020,2021,2022]
and I also have a dictionary that links the sites available in each year(sit_available_year), that looks like following :
2020 -> [ "site1","site2,"site3]
2021 -> [ "site1","site3"]
I’d like to create a dictionary that seems like that:
myDict= Dict(((site,y)) => value1 for y in years, site in sit_available_year[y])
the keys of my dictionary it will be then:
[ "site1", 2020] => value1
[ "site2", 2020] => value1
[ "site1", 2021] => value1
I have tried that syntax above but it doesn’t work. I got an error that says that y is not defined.
Anyone has an idea what’s the right syntax to use? Thanks in advance.
I don’t think you can refer to the value of one of the iterators in the other. Just use a loop:
julia> a = []
0-element Array{Any,1}
julia> for y in 7:8, site in 1:y
push!(a, (site,y) => 4)
end
julia> Dict(a...)
Dict{Tuple{Int64,Int64},Int64} with 15 entries:
(1, 7) => 4
(4, 7) => 4
(6, 8) => 4
(8, 8) => 4
(2, 8) => 4
(5, 8) => 4
(4, 8) => 4
(7, 8) => 4
(1, 8) => 4
(6, 7) => 4
(7, 7) => 4
(3, 7) => 4
(2, 7) => 4
(3, 8) => 4
(5, 7) => 4
(Next time, also make self-contained minimal working examples.)
1 Like
years = [2020,2021]
d = Dict(
2020 => ["site1", "site2", "site3"],
2021 => ["site1", "site3"],
)
Dict((s, y) => 1 for y in years for s in d[y] )
gives you:
Dict{Tuple{String,Int64},Int64} with 5 entries:
("site1", 2021) => 1
("site1", 2020) => 1
("site2", 2020) => 1
("site3", 2021) => 1
("site3", 2020) => 1
8 Likes