Home > Enterprise >  Python dict with conditional keys
Python dict with conditional keys

Time:11-29

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

CodePudding user response:

simply put the values into your dictionary multiple times

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

>>> test["yes"]
200
>>> test["maybe"]
200

CodePudding user response:

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
}

CodePudding user response:

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
  • Related