1

I'm trying to create a dictionary with 1 key that resolves multiple keys per value

my_key = 'a' or 'b'

d = {
    my_key: 'example'
}

print(d.get('a'))

>> 'example'

print(d.get('b'))

>>
 

In the second case it doesn't work. I need to have the same value without replicating the key.

Update I'm trying to avoid the usual way like Brad Day described below:

d = {my_key1:"example", my_key2: "example"}

  • 3
    If you want a value to be available under multiple keys then you need multiple keys with that value. What is the goal of this? We might be able to advise a different approach. – Kemp May 07 '21 at 15:15
  • 4
    It's hard to understand what you're trying to accomplish. `my_key` will always be "a" in your example. – Bafsky May 07 '21 at 15:16
  • 3
    `my_key = 'a' or 'b'` is a logical statement that always returns "a". as Bafsky said. You would need a dictionary like `d = {my_key1:"example", my_key2: "example"}` – Brad Day May 07 '21 at 15:17
  • d = {my_key1:"example", my_key2: "example"} I want to avoid that, to replicate the key. The values of the 2 keys would be the same. So as I understand in your answers this is not possible in a dictionary? I only can do this logic out of the dictionary? – Edoardo Zucchelli May 07 '21 at 15:23
  • You'd have to create some custom dictionary subclass that somehow stores and resolves multiple keys per value. The builtin `dict` can't do that, period. – deceze May 07 '21 at 15:26
  • @deceze yes probably you are right – Edoardo Zucchelli May 07 '21 at 15:30
  • Does [How to properly subclass dict and override __getitem__ & __setitem__](https://stackoverflow.com/questions/2390827/how-to-properly-subclass-dict-and-override-getitem-setitem) answer your question? – wwii May 07 '21 at 15:44

1 Answers1

1

Not sure about achievement but maybe if you have immutable values like strings and want to make sure of unified updates? I.e. that whatever you do to a’s value will be same for b?

di = {'a' : 1, 'b' : 1}


d = {
    1: 'example'
}

print(d[di['a']])
d[di['b']] = "modded"
print(d[di['a']])

output:

example
modded
JL Peyret
  • 10,917
  • 2
  • 54
  • 73