我想知道是否有一種簡單的方法可以在字典中為一個值提供多個鍵。我想要實作的一個例子如下:
class test:
key="test_key"
def __str__(self):
return self.key
tester = test()
dictionary = {}
dictionary[tester] = 1
print(dictionary[tester])
print(dictionary["test_key"])
輸出將是:
>>> 1
>>> 1
我正在尋找的是一種在將物件用作鍵之前自動將其轉換為字串的方法。這可能嗎?
uj5u.com熱心網友回復:
就個人而言,我認為最好將物件顯式轉換為字串,例如
dictionary[str(tester)] = 1
話雖如此,如果您真的 非常 確定要這樣做,請定義 the__hash__和__eq__dunder 方法。無需創建新的資料結構或更改類定義之外的現有代碼:
class test:
key="test_key"
def __hash__(self):
return hash(self.key)
def __eq__(self, other):
if isinstance(other, str):
return self.key == other
return self.key == other.key
def __str__(self):
return self.key
這將輸出:
1
1
uj5u.com熱心網友回復:
幾乎可以肯定你不應該這樣做;只需使用dictionary[str(tester)]. 它更具可讀性,更少驚喜,只需多寫五個字符。
如果你堅持,這是我能想到的最好的
class StrKeyedDict(dict):
def __getitem__(self, key):
return super().__getitem__(str(key))
def __setitem__(self, key, value):
super().__setitem__(str(key), value)
# ... do all the other methods that mess with the key
class Test:
key="test_key"
def __str__(self):
return self.key
tester = Test()
dictionary = StrKeyedDict()
dictionary[tester] = 1
print(dictionary["test_key"])
# => 1
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/465135.html
上一篇:如何從字串中的常見元素創建字典
下一篇:按值對日期字典串列進行排序
