2014-01-26 63 views

回答

5

使用列表理解在字典中的项目,该值过滤你正在寻找:

def keys_of_value(d, value): 
    return [key for key, val in d.items() if val == value] 

用法:

>>> keys_of_value({'a':1,'b':0,'c':1,'d':0}, 0) 
['b', 'd'] 

请注意,这需要你通过所有迭代字典中的项目。如果你需要经常这样做,你可能想建立一个反向查找字典,这与值映射值的所有键的列表:

def reverse_dict(d): 
    res = {} 
    for key, val in d.items(): 
     res.setdefault(val, []).append(key) 
    return res 

用法:

>>> rev = reverse_dict({'a': 1, 'b': 0, 'c': 1, 'd': 0}) 
>>> rev 
{0: ['b', 'd'], 1: ['a', 'c']} 
>>> rev[0] 
['b', 'd'] 
>>> rev[1] 
['a', 'c'] 
>>> rev[2] 
Traceback (most recent call last): 
    File "<stdin>", line 1, in <module> 
KeyError: 2 

现在反向查找与前向查找一样快,但您必须首先构建反向查找字典。

+0

谢谢Clausiu和那些编辑 – user1813564

相关问题