Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Subset of dictionary with aliases

I am looking for a good concise way to find the subset of a dictionary o whose keys contained in the set option_set, or an alias of their key is in the option set.

o = Dict{Symbol,Any}(:a=>2,:b=>1.0,:c=>1//2,:d=>1,:e=>3.0)
options_set = Set([:a :d :f])
aliases = Dict{Symbol,Symbol}(:c=>:d,:b=>:f)
# I want the dictionary of the intersection, including the aliased names
# i.e. Dict(:a=>2,:d=>1,:f=>1.0) or Dict(:a=>2,:d=>1//2,:f=>1.0) (which one is easier?)

#Starting idea
Dict([Pair(k,o[k]) for k in (keys(o) ∩ options_set)]) # Dict(:a=>2)
Dict([Pair(k,o[k]) for k in ((keys(o) ∪ values(aliases)) ∩ options_set)]) # Dict(:a=>2,:d=>1)

Is there a good way to handle using the aliased key to get the right value in the resulting dictionary?


Edit: I realized that it's much easier to just have the aliases in the other direction, i.e.

aliases2 = Dict{Symbol,Symbol}(:d=>:c,:f=>:b)
dict1 = Dict([Pair(k,o[k]) for k in (keys(o) ∩ options_set)])
dict2 = Dict([Pair(k,o[aliases2[k]]) for k in (keys(aliases2) ∩ options_set)])
merge(dict1,dict2)

Still wondering if there's a way of accomplishing the task from the original dictionary which is more direct than inverting it first.

like image 404
Chris Rackauckas Avatar asked Sep 12 '25 04:09

Chris Rackauckas


2 Answers

It might be more performant to invert the dictionary, but you could always just write out the loop.

julia> result = Dict{Symbol, Any}()
Dict{Symbol,Any} with 0 entries

julia> for (k, v) in o
           if k in options_set
               push!(result, k => v)
           elseif haskey(aliases, k)
               push!(result, aliases[k] => v)
           end
       end
Dict{Symbol,Any} with 3 entries:
  :a => 2
  :d => 1
  :f => 1.0
like image 92
Fengyang Wang Avatar answered Sep 13 '25 19:09

Fengyang Wang


This is an old question, but I haven't found answer on 'stackoverflow', so I share the code working in Julia 1.7.2.

"way to find the subset of a dictionary o whose keys contained in the set option_set"

o_result = filter( p -> p[1] in options_set , o)

"or an alias of their key is in the option set."

alias_result = filter( p -> p[2] in options_set, aliases)
like image 31
Stepan S. Sushko Avatar answered Sep 13 '25 20:09

Stepan S. Sushko