根据满足条件的字典中的值创建列表

Creating a list based on the values from a dictionary which satisfy a condition

我有这本字典,我想用 Id 列出一个列表。如果他们的 hasCategory 是 True。

categories = [{'Id': 1350, 'hasCategory': True},
              {'Id': 113563, 'hasCategory': True},
              {'Id': 328422, 'hasCategory': False}]

在这个例子中我的结果列表应该是这样的

list = [1350, 113563]

我正在尝试使用上面的代码

list =[]    
for item in categories:
    if item.hasCategory is True:
        list.push(item.Id) 

但是当我尝试 运行 我的应用程序时出现错误

for item in categories
                       ^
SyntaxError: invalid syntax

您可以在此处使用 list_comprehension。

>>> categories=   [{ 'Id': 1350, 'hasCategory': True},
               { 'Id': 113563, 'hasCategory': True},
               { 'Id': 328422, 'hasCategory': False}]
>>> [i['Id'] for i in categories if i['hasCategory'] == True]
[1350, 113563]

代码中发现的基本问题

  1. 你实际上需要使用:来标记iffor语句的结束,像这样

  2. 不要使用任何内置名称作为变量名。在这种情况下,list.

  3. 要从字典中获取一个值,你只需要使用["key"]方法获取它。点符号将不起作用。


所以你的固定代码看起来像这样

result = []                      # list is a built-in name. Don't use that
for item in categories:          # : at the end
    if item["hasCategory"]:      # : at the end
        result.push(item["Id"])

除此之外,Python检查变量是否真实的 ic 方法只是

if expression:

这就是我们不检查的原因

if item["hasCategory"] == True:

if item["hasCategory"] is True:    # Never use `is` to compare values

引用 PEP-8,Python 代码的风格指南,

Don't compare boolean values to True or False using ==.

Yes:   if greeting:
No:    if greeting == True:
Worse: if greeting is True:

解决这个问题最好的办法就是使用list comprehension加上过滤条件,像这样

>>> [item["Id"] for item in categories if item["hasCategory"]]
[1350, 113563]

它只会根据您的旧可迭代对象创建一个新列表,在本例中为 categories

你应该在你的循环之后有“:”:

for item in categories: