[英]Get value of dict key without iterating items
我有一個字典,其中的鍵是類類型。 此類的__eq__
方法的實現使得在比較過程中忽略了一些類元素:
class ID:
def __init__(self, name, location):
self.name = name
self.location = location
def __eq__(self, other):
return self.name == other.name
def __hash__(self):
return hash(self.name)
我使用dict來查找這個類的元素,不管location
元素的值是什么:
types = {ID("foo", "<stdin>:2:5"): "some data", ID("bar", "<stdin>:10:5"): "other data"}
search = ID("foo", "<stdin>:11:5")
if search in types:
print(f"duplicate entry {search.name}")
但是,當我想要存儲在 dict中的鍵的location
值時,我需要遍歷 dict:
if search in types:
print(f"duplicate entry {search.name}")
r = [k for k, _ in types.items() if k == search][0]
print(f"previous location: {r.location}")
有沒有更好的方法從另一個鍵(被認為是相等的)獲取字典的鍵對象?
編輯:我只對 Python 3 感興趣。
您可以將鍵對象存儲為值的一部分:
# store the value and key as a tuple
lookup_types = {k: (k, v) for k, v in types.items()}
if search in lookup_types:
print(f"duplicate entry {search.name}")
r, _ = lookup_types[search]
print(f"previous location: {r.location}")
輸出
duplicate entry foo
previous location: <stdin>:2:5
你有沒有試過用這段代碼直接獲取屬性?
search.location
或者
types[search].location
這會給你你正在尋找的價值。
您可以創建一個 dict 子類來為您找到重復的鍵
class ID:
def __init__(self, name, location):
self.name = name
self.location = location
def __eq__(self, other):
return self.name == other.name
def __hash__(self):
return hash(self.name)
class MyDict(dict):
def getSimilarKey(self, key):
for k in self.keys():
if k == key:
return k
return None
@classmethod
def create(cls, d):
tmp = cls()
tmp.update(d)
return tmp
types = MyDict.create({ID("foo", "<stdin>:2:5"): "some data", ID("bar", "<stdin>:10:5"): "other data"})
search = ID("foo", "<stdin>:11:5")
if search in types:
print(f"duplicate entry {search.name}")
print(f"previous location: {types.getSimilarKey(search).location}")
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.