Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create array of values based on dictionary and array of keys

Tags:

julia

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?

like image 510
han-tyumi Avatar asked Dec 17 '22 15:12

han-tyumi


1 Answers

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.

like image 195
Nils Gudat Avatar answered Jun 10 '23 00:06

Nils Gudat