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

如何在字典列表中添加值?——向Alex的爱好列表新增爱好遇阻

给字典列表中指定用户的爱好列表添加新项

要给players列表里Alex的爱好列表新增项,核心是先定位到Alex对应的字典,再对其hobbies列表执行添加操作。以下是具体实现:

实现代码

players = [
    {'name': 'Ben', 'age': 31, 'country': 'France', 'hobbies': ['coding', 'biking']},
    {'name': 'Quinn', 'age': 26, 'country': 'Ireland', 'hobbies': ['skiing']},
    {'name': 'Sasha', 'age': 24, 'country': 'Lebanon', 'hobbies': ['sports']},
    {'name': 'Alex', 'age': 28, 'country': 'Austria', 'hobbies': []}
]

# 遍历列表找到Alex的字典条目
for player in players:
    if player['name'] == 'Alex':
        # 给hobbies列表添加新爱好(示例为'reading')
        player['hobbies'].append('reading')
        break  # 找到目标后停止遍历,提升效率

执行结果

运行上述代码后,players中Alex的hobbies会更新为['reading'],完整输出如下:

print(players)
# 输出:
# [
#     {'name': 'Ben', 'age': 31, 'country': 'France', 'hobbies': ['coding', 'biking']},
#     {'name': 'Quinn', 'age': 26, 'country': 'Ireland', 'hobbies': ['skiing']},
#     {'name': 'Sasha', 'age': 24, 'country': 'Lebanon', 'hobbies': ['sports']},
#     {'name': 'Alex', 'age': 28, 'country': 'Austria', 'hobbies': ['reading']}
# ]

为什么你之前的方法没成功?

  • get方法:如果没有先定位到Alex的字典,直接调用get无法精准操作目标列表;即使拿到了hobbies,如果没执行列表的append操作,也不会新增内容。
  • update方法:这个方法是用来更新字典的键值对(比如新增/修改字典的键),但hobbies是列表类型,要给列表加元素得用列表的append/extend,而非字典的update。
  • 键索引操作:如果直接用players[3]['hobbies'].append(...),虽然能生效,但依赖Alex在列表中的固定索引位置,一旦列表顺序变动就会出错,远不如按name查找可靠。

内容的提问来源于stack exchange,提问作者Rafael Zanarino Lobo

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.25 12:28:17