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
这将返回字典中匹配值的列表.
希望这可以帮助! 🙂