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

Python如何用列表推导式从字典列表分别提取各键对应值

列表推导式提取字典列表字段问题修复

需求

从存储城镇信息的字典列表中,分别提取城镇名称、对应人口为两个独立列表,要求使用列表推导式实现。

原有错误代码

towns = [{'name': 'Manchester', 'population': 58241}, 
         {'name': 'Coventry', 'population': 12435}, 
         {'name': 'South Windsor', 'population': 25709}]

print('Name of towns in the city are:', [item for item in towns[item]['name'].values()])
print('Population of each town in the city are:', [item for item in towns[item]['population'].values()])

错误原因

  • 迭代逻辑错误:列表推导式需要先遍历整个towns列表,每次取出的单个元素就是单条城镇字典,不需要用迭代变量做towns的索引,也不需要调用values()方法,直接读取字典对应键的值即可。
  • 变量引用顺序错误:迭代变量item是在for关键字后才定义的,在迭代对象位置写towns[item]会直接触发NameError,因为此时item还没有被赋值。

修正后代码

towns = [{'name': 'Manchester', 'population': 58241}, 
         {'name': 'Coventry', 'population': 12435}, 
         {'name': 'South Windsor', 'population': 25709}]

print('Name of towns in the city are:', [town['name'] for town in towns])
print('Population of each town in the city are:', [town['population'] for town in towns])

运行结果

运行代码后将得到符合预期的输出:

Name of towns in the city are: ['Manchester', 'Coventry', 'South Windsor']
Population of each town in the city are: [58241, 12435, 25709]

列表推导式基础语法为[目标值表达式 for 迭代变量 in 可迭代对象],迭代变量会依次遍历可迭代对象的每一个元素,目标值表达式只需要基于当前迭代到的元素做取值计算即可。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.03 10:03:43