我想創建一個字典,其中多個不同的鍵將映射到相同的值。我看過這個問題,但還是有點不滿意。我想要這種行為:
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
uj5u.com熱心網友回復:
您可以使用dict.fromkeyswhich 生成您想要的內容:
>>> print( dict.fromkeys(['yes', 'maybe'], 200) )
{'yes': 200, 'maybe': 200}
要將其與其他值結合使用,您可以使用**運算子(解包):
test = {
**dict.fromkeys(['yes', 'maybe'], 200),
'no': 100
}
uj5u.com熱心網友回復:
只需將值多次放入字典中
test = {
"yes": 200,
"maybe": 200,
"no": 100,
}
>>> test["yes"]
200
>>> test["maybe"]
200
uj5u.com熱心網友回復:
如果您希望兩個鍵都指向相同的值,而不是使值相同,則另一個潛在的解決方案是,您可以使用兩個字典。第一個存盤您的值,第二個參考這些值。這允許您更改共享值并仍然讓它們共享相同的值。
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
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/368889.html
