2

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?

Cameron Bieganek
  • 7,208
  • 1
  • 23
  • 40
Ricoter
  • 665
  • 5
  • 17
  • 7
    https://github.com/scheinerman/Bijections.jl defines a type for this (but it's just backed by multiple Dicts, so basically what you are suggesting) – Eric Sep 20 '21 at 13:53
  • 2
    This may be obvious but Bijections is more appropriate for bijections than just 2 `Dict`s because it checks for non-injective inputs. Take the one-way mapping `Dict(1 => 3, 2 => 3)`. The attempted inverse `Dict(3 => 1, 3 => 2)` has a repeated key and ends up as `Dict(3 => 2)`. It doesn't seem difficult to implement this check yourself, but there's several other functionalities the library does for you too. – BatWannaBe Sep 20 '21 at 20:59
  • 1
    @Eric, you could turn your comment into an answer with an example of how to use Bijections.jl. :) – Cameron Bieganek Sep 21 '21 at 16:49
  • I don't really like StackOverflow's strict policies about answers vs comments so I don't think I will. Anyone should feel free to add it as an answer though :). – Eric Sep 23 '21 at 11:50

1 Answers1

2

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
Cameron Bieganek
  • 7,208
  • 1
  • 23
  • 40