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

如何使用Python遍历字典列表输出指定格式的选民统计语句

错误原因

  • 不需要嵌套第二层for循环,外层循环已经遍历得到每个单条的县数据字典counties_dict
  • dict.values()方法不接受参数,也不能直接传key获取值,正确的字典取值方式是字典[键名]或者字典.get(键名)
  • 原输出代码里的county是小写,和要求的输出格式里首字母大写的County不匹配

正确实现代码

for counties_dict in voting_data:
    # 直接按键名取出对应的值
    county_name = counties_dict["county"]
    voter_count = counties_dict["registered_voters"]
    # 格式化输出,千位分隔符语法保持你原来的正确写法
    print(f"{county_name} County has {voter_count:,} registered voters")

如果追求更简洁的写法,也可以直接在f-string里取值:

for counties_dict in voting_data:
    print(f"{counties_dict['county']} County has {counties_dict['registered_voters']:,} registered voters")

输出结果

运行后会依次输出你需要的内容:

Arapahoe County has 422,829 registered voters
Denver County has 463,353 registered voters
Jefferson County has 432,438 registered voters

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.04 10:45:01