2013-04-03 31 views
4

例如讓我們說我們有以下的解釋:如何在Python的字典中打印給定值的鍵?

dictionary = {'A':4, 
       'B':6, 
       'C':-2, 
       'D':-8} 

你怎麼能打印賦予它的價值一定的鑰匙嗎?

print(dictionary.get('A')) #This will print 4 

你該怎麼做倒退?即不是通過引用該鍵來獲取值,而是通過引用該值來獲得鍵。

+3

可能出現[在字典中按值獲取鍵值]的重複(http://stackoverflow.com/questions/8023306/get-key-by- value-in-dictionary) –

回答

12

我不相信有辦法做到這一點。這不是如何使用字典... 相反,你將不得不做類似的事情。

for key, value in dictionary.items(): 
    if 4 == value: 
     print key 
+0

+1,特別是因爲許多鍵都可以包含搜索值 –

+1

我想因爲我使用python 3,它應該是items()而不是iteritems()。謝謝你的工作。 – Jett

+0

我認爲你是對的.items(),我會編輯它到我的答案。 – SlxS

1

本詞典是由組織:鍵 - >值

如果你嘗試去:值 - >鍵

然後你有幾個問題;重複,並且有時還會有一本字典包含大量(或不可干擾)的對象,而這些對象不會作爲關鍵字。


但是,如果你仍然想這樣做,你可以通過循環類型的字典鍵和值和匹配他們這樣做很容易如下:

def method(dict, value): 
    for k, v in dict.iteritems(): 
     if v == value: 
      yield k 
# this is an iterator, example: 
>>> d = {'a':1, 'b':2} 
>>> for r in method(d, 2): 
    print r 

b 

正如一位著名的評論,整個事情可以寫成一個生成器表達式:

def method(dict, value): 
    return (k for k,v in dict.iteritems() if v == value) 

Python版本注意:在Python 3+中,您可以使用dict.items()而不是dict.iteritems()

+4

或者,只是'返回(K爲K,V在d.iteritems()如果V ==值)' – nneonneo

+0

@nneonneo是的,但我在這裏使用一個更簡單的例子。 –

+1

不僅大,而且難以置信的對象(如大多數集合)將導致問題。 – phg