我正在寫一個函數,我需要分析一個字典並將其中的一個鍵及其所有值拉出並返回。從字典中返回特定的鍵和它的值
例詞典:
{'P':[("Eight",1460, 225.0, 200.0, "fresco","Netherlands"),
("Six",1465,81.0, 127.1, "tempera", "Netherlands")],
'V':[("Four",1661, 148.0, 257.0,"oil paint", "Austria"),
("Two",1630, 91.0, 77.0, "oil paint","USA")],
'K':[("Five",1922,63.8,48.1,"watercolor","USA"),
("Seven",1950,61.0,61.0,"acrylic paint","USA"),
("Two",1965,81.3,100.3,"oil paint","United Kingdom")],
'C':[("Ten",1496,365.0,389.0,"tempera","Italy")],
'U':[("Nine",1203,182.0, 957.0,"egg tempera","Italy"),
("Twelve",1200,76.2,101.6,"egg tempera","France")]}
所以,如果我的函數被調用find_the_key,我一直在尋找「C」和它的值,那麼就需要返回
find_the_key(dictionary2(),['C'])
return {'C': [('Ten', 1496, 365.0, 389.0, 'tempera','Italy')]}
如果需要找到'C'和'V'會返回
find_the_key(dictionary2(),['C','V'])
return {'C': [('Ten', 1496, 365.0, 389.0, 'tempera', 'Italy')], 'V': [('Four',
1661, 148.0, 257.0, 'oil paint', 'Austria'), ('Two', 1630, 91.0, 77.0, 'oil
paint', 'USA')]}
我已經做了一些關於從字典和我現在的代碼可能很接近。
def find_the_key(dictionary,thekey):
for thekey in dictionary.keys():
if dictionary[thekey] == targetkey:
return key, targetkey
目前我得到的錯誤targetkey沒有定義,雖然我認爲我的邏輯是在正確的軌道上。有沒有人有任何想法如何做到這一點?
如果密鑰不存在於字典中,您想怎麼做?只要忽略它,引發錯誤,或返回默認值? –
@ PM2Ring讓 - 弗朗索瓦法布爾的解決方案做的是正確的事情,我認爲它只是忽略它 – warrior4223
我相信這兩個答案都可以處理問題,甚至不知道它:) –