2011-03-10 73 views
1

我有哈希:如何通過值知道散列鍵?

test = { 
    'a': ['localhost'], 
    'b': ['bb','aa'], 
    'c': ['cc'] 
} 

例如,我想知道BB的關鍵? (b)中。

+0

這可能有所幫助:http://stackoverflow.com/questions/3282823/python-get-key-with-the -least-value-from-a-dictionary – Nope 2011-03-10 14:52:58

回答

4

一般來說,你可以構建一個反向的字典是這樣的:

test_reversed = dict((v, k) for k, values in test.iteritems() for v in values) 
+1

Not on python v3 + ... would be'test.items()'而不是'test.iteritems()' – dawg 2011-03-11 00:30:47

2

假設恰好有一個關鍵的匹配,可以使用

key = next(k for k in test if "bb" in test[k]) 

這遍歷所有的鍵,直到分配列表中包含你在找什麼。這個操作比用鍵查找效率要低很多,這是字典的目的。

3

除了遍歷鍵和值之外,還沒有簡單的方法來完成此操作。如果你需要做這個有很多,這將是值得構建反向映射爲一次性的,所以你可以去查找:

from collections import defaultdict 

reversed_test = defaultdict(set) 
test = { 'a': ['localhost'], 'b': ['bb','aa'], 'c': ['cc'] } 

for k, v in test.items(): 
    for i in v: 
     reversed_test[i].add(k) 

print reversed_test['bb'] 

reversed_test字典映射一個關鍵,例如'bb'一組最初映射到包含'bb'的列表的字符串。這比Space_C0wb0y's neat solution簡潔的要少得多,因爲我是假設有可能爲test的樣子:

{'a': ['foo','bar','foo'], 'b': ['foo','quux'] } 

換句話說:

  • 多個鍵可能映射到包含'foo'
  • 'foo'名單可能會在列表中多次出現。
相關問題