Dicts with more than one key?

Is there a standard way to create a Dict with more than one key? Or one needs to unavoidably create multiple Dicts by hand?

Something like (I’m inventing here the notation):

letters = Dict{Keys{Char,Char},String}(
    Keys('a','A') => "This is letter A",
    Keys('b','B') => "This is letter B",
)

julia> letters['a']
This is letter A

julia> letters['A']
This is letter A

etc.

Not that I know of? Of course, you can simply add multiple keys with the same value to a single dictionary, ala s = "This is letter A"; letters['a'] = letters['A'] = s.

It seems better to have a function that canonicalizes your keys before you pass them to the dictionary, or similarly have a custom hashing and equality function. In your example, it is as simple as letters[lowercase(c)]

3 Likes

I don’t think there’s a standard way to do that. If you control the type that is used for the keys, you could ensure that seemingly different keys hash the same. For example, you could make a string macro k"a" that produces a Key("a"), and then you can define hash in such a way that hash(Key("a")) == hash(Key("A")).

1 Like

Yeah, something like those ideas is simple enough. :slight_smile:

To make that completely hidden one could create a new type of Dict and overwrite getindex, I guess, but in my case it is an internal convenience, so not worth the effort.

Thanks both!

This looks close enough to your wished syntax:

letters = Dict([['a','A'] .=> "This is letter A";
                ['b','B'] .=> "This is letter B"])

letters['a']        # "This is letter A"
letters['A']        # "This is letter A"
3 Likes

:slight_smile: Changing the solution! That is really simple and concise.