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

如何用Python列表推导式实现字典键值映射生成符合筛选条件的新字典列表

你的代码存在两个问题:

  • 你写的{dictionary['new_age'],dictionary['new_email']}是集合的语法,不是字典结构,所以只能存储独立的值,没有键值对映射关系
  • 原字典中不存在new_age、new_email这两个键,直接取值会触发键错误,你需要从原字典的age、email键取值,再绑定到新的键名上

正确的列表推导写法如下:

entries = [{'age': 65, 'name': 'Tim', 'email': 'tim@bob.com'},{'age': 72, 'name': 'Andy', 'email': 'andy@bob.com'},{'age': 50, 'name': 'Bob', 'email': 'bob@bob.com'}, {'age': 30, 'name': 'Shelly', 'email': 'shelly@shelly.com'}]

x = [{'new_age': item['age'], 'new_email': item['email']} for item in entries if item['age'] >= 50]

打印x即可得到你期望的输出:

[{'new_age': 65, 'new_email': 'tim@bob.com'}, {'new_age': 72, 'new_email': 'andy@bob.com'}, {'new_age': 50, 'new_email': 'bob@bob.com'}]

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.08 06:36:03