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.

dict = {['name1', 'name2'] : 'value1'}
print(dict.get('name1)) 

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

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

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

def foobar():
    pass

def spameggs():
    pass

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))
User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement