Python dict with conditional keys

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

3 answers

  • answered 2021-11-29 00:42 ti7

    simply put the values into your dictionary multiple times

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

  • answered 2021-11-29 00:43 Pedro Maia

    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
    }
    

  • answered 2021-11-29 00:51 jezza_99

    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
    

How many English words
do you know?
Test your English vocabulary size, and measure
how many words do you know
Online Test
Powered by Examplum