Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to reverse a dictionary in Julia?

If I have a dictionary such as

my_dict = Dict(
    "A" => "one",
    "B" => "two",
    "C" => "three"
  )

What's the best way to reverse the key/value mappings?

like image 871
Scott Warchal Avatar asked Nov 19 '16 14:11

Scott Warchal


1 Answers

One way would be to use a comprehension to build the new dictionary by iterating over the key/value pairs, swapping them along the way:

julia> Dict(value => key for (key, value) in my_dict)
Dict{String,String} with 3 entries:
  "two"   => "B"
  "one"   => "A"
  "three" => "C"

When swapping keys and values, you may want to keep in mind that if my_dict has duplicate values (say "A"), then the new dictionary may have fewer keys. Also, the value located by key "A" in the new dictionary may not be the one you expect (Julia's dictionaries do not store their contents in any easily-determined order).

like image 97
Alex Riley Avatar answered Sep 29 '22 22:09

Alex Riley