Python 带条件键的字典

Python dict with conditional keys

我想创建一个字典,其中多个不同的键将映射到相同的值。我看过,但还是有点不尽如人意。我想要这种行为:

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

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

相反,我得到了这种行为。有趣的是 dict 完全可以初始化。这是怎么回事?

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

只需多次将值放入字典

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

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

您可以使用 dict.fromkeys 来生成您想要的内容:

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

要将它与其他值组合,您可以使用 ** 运算符(拆包):

test = {
     **dict.fromkeys(['yes', 'maybe'], 200),
     'no': 100
}

另一个可能的解决方案是,如果您希望两个键都指向相同的值,而不是让值相同,您可以使用两个字典。第一个存储您的值,第二个引用这些值。这允许您更改共享值并仍然让它们共享相同的值。

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