繁体   English   中英

从词典列表中选择具有特定字段值的项目(类似于SQL SELECT命令)

[英]Select items with specific field values from a list of dictionaries (similar to SQL SELECT command)

假设我们有一个这样的字典列表:

mylist=[{'word':'bear','category':'animal'},
        {'word':'lion','category':'animal'},
        {'word':'ant','category':'insect'},
        {'word':'ladybug','category':'insect'}]

我想将具有'category':'animal'项目选择到新列表中,就像我通常在模型SQL中所做的那样: SELECT * FROM mylist WHERE 'category'='insect'

结果将是:

newlist=[{'word':'ant','category':'insect'},
        {'word':'ladybug','category':'insect'}]

如何在Python 2.7中做到这一点? 我知道我可以使用for循环来做到这一点(每个人都知道:)),但是我想有一种更干净的方法可以做到这一点。

您可以使用带有“ if”语句的列表理解来快速完成。

您的原始列表对象:

mylist=[{'word':'bear','category':'animal'},
        {'word':'lion','category':'animal'},
        {'word':'ant','category':'insect'},
        {'word':'ladybug','category':'insect'}]

列表理解以创建新列表对象,其中“类别”键的值为“昆虫”:

newlist = [dict for dict in mylist if dict["category"] == "insect"]

结果:

[{'category': 'insect', 'word': 'ant'},
{'category': 'insect', 'word': 'ladybug'}]

列出的字典对象将自动按字母顺序对其进行排序,但是答案在结构上仍然相同。 我希望这有帮助!

使用列表理解

newlist = [item for item in mylist if item['category'] == 'insect']

这会遍历输入列表中的所有元素,仅包括那些与if表达式匹配的元素。

演示:

>>> mylist=[{'word':'bear','category':'animal'},
...         {'word':'lion','category':'animal'},
...         {'word':'ant','category':'insect'},
...         {'word':'ladybug','category':'insect'}]
>>> [item for item in mylist if item['category'] == 'insect']
[{'category': 'insect', 'word': 'ant'}, {'category': 'insect', 'word': 'ladybug'}]
>>> [item for item in mylist if item['category'] == 'animal']
[{'category': 'animal', 'word': 'bear'}, {'category': 'animal', 'word': 'lion'}]
>>> [item for item in mylist if item['word'] in ('bear', 'ladybug')]
[{'category': 'animal', 'word': 'bear'}, {'category': 'insect', 'word': 'ladybug'}]

试试这个

newlist=[x for x in mylist if x['category']=='animal']

这是一种功能样式的解决方案,无需显式编码for循环。

定义一个函数,该函数将返回一个将字典值与指定值进行比较的布尔值。

import functools, pprint
def foo(d, key, value):
    return d[key] == value

使用functools.partial创建符合您要求的过滤器

# category filter
animal = functools.partial(foo, key = 'category', value = 'animal')
# word filter
ant = functools.partial(foo, key = 'word', value = 'ant')

在整个程序中使用这些过滤器

pprint.pprint(filter(animal, mylist))

>>>
[{'category': 'animal', 'word': 'bear'},
 {'category': 'animal', 'word': 'lion'}]
>>>

pprint(filter(ant, mylist))

>>>
[{'category': 'insect', 'word': 'ant'}]
>>> 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM