我有一个字典,每个键在列表中有多个值。 任务是:
通过使用if条件实现任务1:
if (word in dictionary[topics] for topics in dictionary.keys())
我想在if条件评估为True时获取主题。像
这样的东西if (word in dictionary[topics] for topics in dictionary.keys()):
print topics
答案 0 :(得分:3)
您可以使用列表推导(类似于压缩的for
循环)。它们更易于编写,并且在某些情况下可以更快地进行计算:
topiclist = [topic for topic in dictionary if word in dictionary[topic]]
您不需要dictionary.keys()
因为dict
已经是可迭代对象;迭代它将无论如何产生键,并且(在Python 2中)以比dictionary.keys()
更有效的方式。
修改强> 这是另一种方法(它避免了额外的字典查找):
topiclist = [topic for (topic, tlist) in dictionary.items() if word in tlist]
避免额外的字典查找可能会让它更快,尽管我还没有测试过它。
在Python 2中,为了提高效率,您可能希望这样做:
topiclist = [topic for (topic, tlist) in dictionary.iteritems() if word in tlist]
答案 1 :(得分:1)
if (word in dictionary[topics] for topics in dictionary.keys())
上面一行的问题在于,您正在创建一个生成器对象,用于评估word
是否在dictionary
的每个值中,并为每个值返回一个bool。由于非空列表始终为true,因此无论单词是否在值中,此if语句始终为true。你可以做两件事:
使用any()
会使您的if
声明有效:
if any(word in dictionary[topics] for topics in dictionary.keys()):
但是,这并不能解决捕获键值的初始问题。所以相反:
使用实际的列表推导,使用预定义(我假设)变量word
作为排序过滤器:
keys = [topics for topics in dictionary if word in dictionary[topics]]
或
使用filter()
keys = filter(lambda key: word in dictionary[key],dictionary)
这两者都做同样的事情。提醒一下,迭代dictionary
和dictionary.keys()
是等效的
请注意,这两个方法都会返回包含word
值的所有键的列表。使用常规列表项访问每个键。
答案 2 :(得分:0)
听起来您正在搜索的单词只能在一个键中找到。正确的吗?
如果是这样,您可以迭代字典的键值对,直到找到包含搜索词的键。
对于Python 2:
body = {
:snippet => {
:videoId => videoId,
:language => "en",
:name => "English"
}
}
captions_insert_response = client.execute(
:api_method => youtube.captions.insert,
:body_object => body,
:media => Google::APIClient::UploadIO.new(captions_file, 'text/xml'),
:parameters => {
'uploadType' => 'multipart',
:part => body.keys.join(',')
}
)
对于Python 3,只需将found = False
for (topic, value) in dictionary.iteritems():
if word in topic:
found = True
print topic
break
替换为iteritems()
。