Array of Dict to array of String

Having array of Dict, e.g.

x1 = [Dict("a"=>"a", "b"=>"b", "c"=>"c"), Dict("a"=>"e", "b"=>"f", "c"=>"g"), Dict("a"=>"h", "b"=>"i", "c"=>"j")]

What would be the most efficient way to convert it to array of strings consisting only of values of Dict item “a”. (We can safely assume that each Dict in input array contains item “a”)

I mean to get a result (based on example above) like this:

["a", "e", "h"]

Thank you,

I think this should work, although I don’t know if it is the most efficient way

things = [d["a"] for d in x1 if haskey(d, "a")]

(not actually tested)

Broadcasting seems slightly more efficient than [d["a"] for d in x1] from my testing:

getindex.(x1, "a")

Thank you both. With for loop (1st solution) it takes for me 0.042684 seconds (69.95 k allocations: 3.495 MiB). With getindex. it takes 0.000015 seconds (4 allocations: 192 bytes).

Good catch. The only thing left to say is that broadcast fails when any of the Dicts does not contain “a”. As long as that’s not the case, broadcasting is the best way

Edit: nvm, I just reread the question and he did say that all dicts do contain “a” here

you could use also this

get.(x1,“a”,“NA”)