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
相关产品推荐
相关产品推荐

