从列表中查找哪些字典包含单词 [英] Find which dictionaries from a list contain word

查看:828
本文介绍了从列表中查找哪些字典包含单词的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个字典,每个键在列表中有多个值。
这些任务是:


  1. 检测给定的单词是否在字典值中

  2. 如果它是真的,则从字典中返回相应的键

任务1通过使用if条件来实现: ($)
$ b

  if(在dictionary.keys()中的主题的词典[主题]中)

我想在if条件计算为True时获得主题。类似于

  if(在dictionary.keys()中主题的词典[主题]中):
打印主题


解决方案

您可以使用列表理解压缩循环)。它们更容易编写,在某些情况下计算速度更快:

  topiclist = [主题词典主题if word in字典[topic]] 

您不需要 dictionary.keys() 因为 dict 已经是一个可迭代的对象;迭代它将无论如何会产生密钥,并且(在Python 2中)比 dictionary.keys()更有效。

编辑:
这是另一种方法(避免额外的字典查找):

 topiclist = [dictionary.txt中的(topic,tlist)的主题(如果在tlist中的单词)

在Python 2中,出于效率的考虑,为避免额外的字典查找,可能会使速度更快,尽管我还没有对其进行测试。你可以这样做:

$ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $主题词表]


I have a dictionary with each keys having multiple values in a list. The tasks are:

  1. To detect whether a given word is in the dictionary values
  2. If it is true, then return the respective key from the dictionary

Task 1 is achieved by using an if condition:

if (word in dictionary[topics] for topics in dictionary.keys())

I want to get the topics when the if condition evaluates to be True. Something like

if (word in dictionary[topics] for topics in dictionary.keys()):
   print topics

解决方案

You can use a list comprehension (which is like a compressed for loop). They are simpler to write and can in some circumstances be faster to compute:

topiclist = [topic for topic in dictionary if word in dictionary[topic]]

You don't need dictionary.keys() because a dict is already an iterable object; iterating over it will yield the keys anyway, and (in Python 2) in a more efficient way than dictionary.keys().

EDIT: Here is another way to approach this (it avoids an extra dictionary look up):

topiclist = [topic for (topic, tlist) in dictionary.items() if word in tlist]

Avoiding the extra dictionary lookup may make it faster, although I haven't tested it.

In Python 2, for efficiency sake, you may want to do:

topiclist = [topic for (topic, tlist) in dictionary.iteritems() if word in tlist]

这篇关于从列表中查找哪些字典包含单词的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆