我在写一个函数,我需要分析一个字典,拿出其中一个键和它的所有值并返回它。
示例词典:{'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
目前我得到的错误目标键没有定义,虽然我认为我的逻辑是正确的轨道。有人知道怎么做吗?