0

I'd like to create a dict where multiple different keys will map to the same value. I have seen this question, but it's still a little unsatisfying. I would like this behavior:

test = {
    'yes' or 'maybe': 200,
    'no': 100
}

test['yes']
--> 200
test['maybe']
--> 200
test['no']
--> 100

Instead, I get this behavior. It's interesting that the dict can init at all. What is going on here?

test = {
    'yes' or 'maybe': 200,
    'no': 100
}
test['yes']
--> 200
test['maybe']
--> KeyError
test['no']
--> 100

# If I change to and:

test = {
    'yes' and 'maybe': 200,
    'no': 100
}
test['yes']
--> KeyError
test['maybe']
--> 200
test['no']
--> 100
Wesley Cheek
  • 1,058
  • 12
  • 22
  • 2
    `'yes' or 'maybe'` is an expression that evaluates to `'yes'`. This is just normal Python boolean behavior, dictionaries have nothing to do with it. – jasonharper Nov 29 '21 at 00:39
  • 1
    `and` and `or` are boolean conditional operators. You can't use them to define multiple mappings for the same value; they always evaluate to one of the two values (the last value that had to be evaluated to determine the truthiness of the expression). – ShadowRanger Nov 29 '21 at 00:39

3 Answers3

1

simply put the values into your dictionary multiple times

test = {
    "yes":   200,
    "maybe": 200,
    "no":    100,
}

>>> test["yes"]
200
>>> test["maybe"]
200
ti7
  • 16,375
  • 6
  • 40
  • 68
1

You can use dict.fromkeys which generate what you want:

>>> print( dict.fromkeys(['yes', 'maybe'], 200) )
{'yes': 200, 'maybe': 200}

To combine it with additional values you can use ** operator (unpacking):

test = {
     **dict.fromkeys(['yes', 'maybe'], 200),
     'no': 100
}
Pedro Maia
  • 2,666
  • 1
  • 5
  • 20
1

Another potential solution if you want both keys to point to the same value, as opposed to having the values be the same, you could use two dictionaries. The first stores your values, the second references these. This allows you to change the shared value and still have them share the same value.

dict_store = {
    "first_value": 200,
    "second_value": 100
}
dict_reference = {
    'yes': "first_value",
    'maybe': "first_value",
    'no': "second_value"
}

>>> print(dict_store[dict_reference['maybe']])
200
>>> dict_store[dict_reference['yes']] = 150
>>> print(dict_store[dict_reference['maybe']])
150
jezza_99
  • 1,074
  • 1
  • 5
  • 17