[英]Search for dictionary key when the keys are tuples
sample = {('red', 'blue', 'purple') : 'color', 'redo' : 'again', 'bred' : 'idk', 'greeting' : ('hi', 'hello')}
def search(c):
if c in sample.keys():
return sample[c]
print(search('red'))
這將返回None
。 我知道我可以將它們分開,並用相同的值制作多個鍵,但是如果可以的話,我真的很想避免這樣做。 我可以嗎?
而且我還希望能夠搜索值(也可能是元組)並獲取相應的鍵。
使用iteritems()
可以為您提供幫助。 如下更新您的search()
方法。 應該工作正常。
def search(c):
for k, v in sample.iteritems():
if type(k) in [list, tuple, dict] and c in k:
return v
elif c == k:
return v
如果字典中出現c
多次,
def search(c):
found = [ ]
for k, v in sample.iteritems():
if type(k) in [list, tuple, dict] and c in k:
found.append(v)
elif c == k:
found.append(v)
return found
這將返回字典中匹配值的列表。
希望這可以幫助! :)
如果您不需要按整個元組('red', 'blue', 'purple')
則可以稍微不同地構建字典:
sample = {e: v for k, v in {('red', 'blue', 'purple') : 'color'}.items()
for e in k}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.