You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python按布尔条件筛选字典并打印投票者名称报错求助

代码错误排查:实现仅打印已投票参与者名称

问题说明

我先创建了参与者元组,接着为每个参与者创建包含多项属性的字典(最后一个键voted为布尔类型),随后将所有参与者字典存入survey_data元组。但在实现仅打印已投票参与者名称的代码(1.4部分)时出现报错,无法正常运行。

报错信息

Traceback (most recent call last):
  File "<input>", line 1, in <module>
TypeError: 'builtin_function_or_method' object is not subscriptable

原代码

#1.1)
participants = ("theo", "anna", "aya", "noah", "jim")

#1.2)
dico = {}
theo = {"name" : "theo", "age" : 23, "town" : "uccle", "ideology" : "conservative", "voted" : False}
anna = {"name" : "anna", "age" : 22, "town" : "ixelles", "ideology" : "centrist", "voted" : True}
aya = {"name" : "aya", "age" : 20, "town" : "bruxelles", "ideology" : "socialist", "voted" : True}
noah = {"name" : "noah", "age" : 22, "town" : "st_gilles", "ideology" : "socialist", "voted" : False}
jim = {"name" : "jim", "age" : 21, "town" : "etterbeek", "ideology" : "liberal", "voted" : True}

# 1.3)
survey_data = (theo, anna, aya, noah, jim)

# 1.4)
for [theo, anna, aya, noah, jim] in survey_data:
    if [theo, anna, aya, noah, jim] ["voted": True]:
        var = print [theo, anna, aya, noah, jim]

错误分析

  1. 循环遍历语法错误:survey_data中的每个元素是单个参与者字典,循环时不需要用列表解构[theo, anna, aya, noah, jim],这会导致Python尝试将单个字典拆解成5个元素,完全不符合数据结构。正确做法是遍历每个字典元素,用单个变量接收。
  2. 条件判断语法错误:[theo, anna, aya, noah, jim] ["voted": True]是完全错误的写法,判断是否已投票应该检查字典中voted键对应的布尔值,即participant["voted"]。
  3. print调用错误:Python3中print是函数,必须用括号调用;且你需要打印的是参与者的name属性,不是整个字典或列表。

修正后的代码

#1.1)
participants = ("theo", "anna", "aya", "noah", "jim")

#1.2)
theo = {"name" : "theo", "age" : 23, "town" : "uccle", "ideology" : "conservative", "voted" : False}
anna = {"name" : "anna", "age" : 22, "town" : "ixelles", "ideology" : "centrist", "voted" : True}
aya = {"name" : "aya", "age" : 20, "town" : "bruxelles", "ideology" : "socialist", "voted" : True}
noah = {"name" : "noah", "age" : 22, "town" : "st_gilles", "ideology" : "socialist", "voted" : False}
jim = {"name" : "jim", "age" : 21, "town" : "etterbeek", "ideology" : "liberal", "voted" : True}

# 1.3)
survey_data = (theo, anna, aya, noah, jim)

# 1.4) 修正后的代码
for participant in survey_data:
    if participant["voted"]:
        print(participant["name"])

运行结果

执行后会输出所有已投票的参与者名称:

anna
aya
jim

内容的提问来源于stack exchange,提问作者Malixa

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.12 01:50:00