Is there a way to add a value to every array in a Dictionary?
julia> d = Dict(:a => 1, :b => [1 2 ; 3 4], :c => "x")
Dict{Symbol, Any} with 3 entries:
:a => 1
:b => [1 2; 3 4]
:c => "x"
julia> for k in keys(d)
if d[k] isa Array
d[k] .+= 1
end
end
julia> d
Dict{Symbol, Any} with 3 entries:
:a => 1
:b => [2 3; 4 5]
:c => "x"
julia>
No, I want to add a zero to every array in my dictionary, not add 1 to every value in my dictionary
d = Dict(:a => 1, :b => [1 2 ; 3 4], :c => "x")
Dict{Symbol, Any} with 3 entries:
:a => 1
:b => [1 2; 3 4]
:c => "x"
Dict{Symbol, Any} with 3 entries:
:a => 1,0
:b => [1 2; 3 4,0]
:c => ["x",0]
It's a pretty simple extrapolation from there
I'm not sure how you mean
You can use any operation, with the same approach.
Nothing changes if you switch from adding 1 to appending a zero.
@brett knoss It would help if you used the standard terminology: a dictionary is made up of keys and values. For example, in Dict("abc" => 42)
, "abc"
is a key and 42
its corresponding value.
So, I assume you have a dictionary where all values are vectors, and you want to append a zero to each one. All you have to do is iterate over the values:
julia> d = Dict(:a => [], :b => [1, 2, 3])
Dict{Symbol, Vector{T} where T} with 2 entries:
:a => Any[]
:b => [1, 2, 3]
julia> for v in values(d)
append!(v, 0)
end
julia> d
Dict{Symbol, Vector{T} where T} with 2 entries:
:a => Any[0]
:b => [1, 2, 3, 0]
Unless you are sure that all values are vectors with elements that are either numerical or Any
, you'll have to be careful with the types:
julia> append!(["a", "b", "c"], 0)
ERROR: MethodError: Cannot `convert` an object of type Int64 to an object of type String
...
julia> append!([1 2 ; 3 4], 0)
ERROR: MethodError: no method matching append!(::Matrix{Int64}, ::Int64)
...
For learning how to generalize things like this there some pretty good introductory resources including books
https://benlauwens.github.io/ThinkJulia.jl/latest/book.html
https://leanpub.com/julia-for-beginners
as well as free classes and excersies
https://juliaacademy.com/courses
https://exercism.io/tracks/julia
For terminology issues like the difference between "add" and "append" this is actually quite consistent between different programming languages, so introductory resources for other languages could be helpful there too.
I think Dictionaries.jl also has an interface that does this more efficiently, if that is needed.
Last updated: Nov 22 2024 at 04:41 UTC