I'm new to Julia, so I'm sorry if this is a basic question.
Say we have a dictionary, and a vector of keys:
X = [2, 1, 1, 3]
d = Dict( 1 => "A", 2 => "B", 3 => "C")
I want to create a new array which contains values instead of keys (according to the dictionary), so the end result would be something like
Y = ["B", "A", "A", "C"]
I suppose I could iterate over the vector elements, look it up in the dictionary and return the corresponding value, but this seems awfully inefficient to me. Something like
Y = Array{String}(undef, length(X))
for i in 1:length(X)
Y[i] = d[X[i]]
end
EDIT: Also, my proposed solution doesn't work if X
contains missing
values.
So my question is if there is some more efficient way of doing this (I'm doing it with a much larger array and dictionary), or is this an appropriate way of doing it?
Efficiency can mean different things in different contexts, but I would probably do:
Y = [d[i] for i in X]
If X
contains missing
values, you could use skipmissing(X)
in the comprehension.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With