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?
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With