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

Tags: ,

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.

dict = {['name1', 'name2'] : 'value1'}


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):

>>> d = {}
>>> d[("foo", "bar")] = 6
>>> d[("foo", "baz")] = 8
>>> d
{('foo', 'bar'): 6, ('foo', 'baz'): 8}
>>> d[("foo", "baz")]

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


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():

def foobar():

def spameggs():

func_to_names = {
  foobar: ("foo", "bar", "fb", "foobar"),
  spameggs: ("spam", "eggs", "se", "breakfast"),
name_to_func = {}
for func, names in func_to_names.items():
    name_to_func.update(dict.fromkeys(names, func))

Source: stackoverflow