【发布时间】:2016-11-13 22:08:52
【问题描述】:
我正在编写一个函数,我需要分析字典并提取其中一个键及其所有值并将其返回。
字典示例:
{'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 is not defined 虽然我认为我的逻辑是正确的。有谁知道如何做到这一点?
【问题讨论】:
-
如果字典中不存在键,你想做什么?只是忽略它,引发错误,还是返回默认值?
-
@PM2Ring Jean-François Fabre 的解决方案是正确的,我认为只是忽略它
-
我相信这两个答案都能在没有注意到的情况下解决问题:)
标签: python python-3.x dictionary find key