2015-08-13 40 views
-1

我正在嘗試編寫一個Python函數,該函數返回aDict中值爲target的密鑰列表。密鑰列表應按升序排列。 aDict中的鍵和值都是整數。 (如果aDict不包含target值,程序應該返回一個空列表。)鍵是a,b,c。我得到一個錯誤消息,說名稱'a'沒有定義。不知道爲什麼我已經將a,b和c聲明爲整數。使用字典中的值查找鍵值

def keysWithValue(aDict, target): 
    ''' 
    aDict: a dictionary 
    target: integer 
    a:integer 
    b:integer 
    c:integer 
    ''' 
    # Your code here 
    i=0 
    j=0  
    if aDict[i]==5: 
     list[j]=aDict[i] 
     i+=1 
     j+=1 
    return list 
+0

這不是變量,在Python中是如何工作的。 –

回答

1

您可以用生成器表達式您target與每個值的比較你的字典的.items()然後,包裹在一個sorted通話。

如果該值是一個整數,你可以使用==

def keysWithValue(aDict, target): 
    return sorted(key for key, value in aDict.items() if target == value) 

>>> d = {'b': 1, 'c': 2, 'a': 1, 'd': 1} 
>>> keysWithValue(d, 1) 
['a', 'b', 'd'] 

或者,如果值是整數的列表,你可以使用in

def keysWithValue(aDict, target): 
    return sorted(key for key, value in aDict.items() if target in value) 

>>> d = {'b': [1,2,3], 'c': [2,5,3], 'a': [1,5,7], 'd': [9,1,4]} 
>>> keysWithValue(d, 1) 
['a', 'b', 'd'] 
+0

OP聲明「aDict中的鍵和值都是整數」。 – martineau

+0

好吧然後第一種方法將爲他們工作 – CoryKramer