Skip to content
Advertisement

Is it possible for a key to have multiple names in a dictionary?

I’m not sure if this is even possible but it’s worth a shot asking.

I want to be able to access the value from indexing one of the values.

The first thing that came to mind was this but of course, it didn’t work.

JavaScript

Advertisement

Answer

You can use a tuple (as it’s immutable) as a dict key if you need to access it by a pair (or more) of strings (or other immutable values):

JavaScript

This isn’t “a key having multiple names”, though, it’s just a key that happens to be built of multiple strings.

Edit

As discussed in the comments, the end goal is to have multiple keys for each (static) value. That can be succinctly accomplished with an inverted dict first, which is then “flipped” using dict.fromkeys():

JavaScript
User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement