1

Is there a compact way to have alternative keys for the same value in a dictionary?

Taking a dictionary like the following

dict={'A':1,'B':2,'one':1,'two':2}

I can obtain the value 1 using two different keys:

dict['A']
dict['one']

I would like to know if there is a more compact way to write it, something akin to:

dict2={['A','one']:1,['B','two']:2}
254
  • 53
  • 4
  • 1
    Does this answer your question? [Is it possible to assign the same value to multiple keys in a dict object at once?](https://stackoverflow.com/questions/2974022/is-it-possible-to-assign-the-same-value-to-multiple-keys-in-a-dict-object-at-onc) – PacketLoss Feb 12 '20 at 23:15
  • Yes, thanks, I still have to try it but it looks fine. – 254 Feb 12 '20 at 23:26

1 Answers1

1

You can define the dict with keys of the same value grouped as a tuple first:

d = {('A', 'one'): 1, ('B', 'two'): 2}

so that you can then convert it to the desired dict with:

d = {key: value for keys, value in d.items() for key in keys}

d becomes:

{'A': 1, 'one': 1, 'B': 2, 'two': 2}
blhsing
  • 91,368
  • 6
  • 71
  • 106
  • 1
    Thanks, this looks like a simple way to do it, even with a large number of keys. – 254 Feb 12 '20 at 23:27