Search code examples
dictionaryjulia

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?


Solution

  • 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).