I have some problem where I need to define a one-to-one mapping from one variable to another. I am using a Dictionary like this:
mapping = Dict('I'=>1, 'V'=>5, 'X'=>10)
I also want to map it back, so at the moment I define a second Dict:
inverse_mapping = Dict(1=>'I', 5=>'V', 10=>'X')
Is there a better collection for this out there? something like a two way dictionary or maybe another kind of hash table?
You can use Bijections.jl. Here is an example of the usage.
First create an empty bijection mapping Int to Int, and then add a couple pairs to the bijection:
using Bijections.jl
b = Bijection{Int,Int}()
b[1] = 101
b[2] = 102
To find the value associated with a key, use the normal dictionary indexing syntax:
julia> b[1]
101
To find the key associated with a value, use function call syntax (note the parentheses instead of square brackets):
julia> b(101)
1
Bijections can also be iterated over like a dictionary:
julia> [k + v for (k, v) in b]
2-element Vector{Int64}:
104
102
Finally, you can see that Bijection disallows adding a pair that would break the bijective map:
julia> b[3] = 101
ERROR: One of x or y already in this Bijection
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