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

如何简化字典列表中指定元素的属性更新代码?

问题:简洁更新字典列表中指定元素的属性

我有如下字典列表:

list_dict = [
        {'name': 'Old Ben', 'age': 71, 'country': 'Space', 'hobbies': ['getting wise']},
        {'name': 'Han', 'age': 26, 'country': 'Space', 'hobbies': ['shooting']},
        {'name': 'Luke', 'age': 24, 'country': 'Space', 'hobbies': ['being arrogant']},
        {'name': 'R2', 'age': 'unknown', 'country': 'Space', 'hobbies': []}
    ]

需要为其中name为'R2'的元素更新hobbies属性,当前已实现的代码如下:

for i in range(len(list_dict)):
    people = list_dict[i]
    if people['name'] == 'R2':
        people['hobbies'] = ['lubrication']
print(list_dict)

虽然能得到预期结果,但希望学习更简洁的代码写法。


简洁写法方案

方案1:直接遍历列表元素

不需要通过索引遍历,直接迭代列表里的每个字典,代码更简洁直观:

for person in list_dict:
    if person['name'] == 'R2':
        person['hobbies'] = ['lubrication']
print(list_dict)

去掉了多余的索引变量i,直接操作列表中的字典对象,逻辑更清晰。

方案2:用next()快速定位目标元素

如果确定列表中存在且只存在一个'R2',可以用生成器表达式结合next()直接找到目标字典,修改属性:

r2 = next(p for p in list_dict if p['name'] == 'R2')
r2['hobbies'] = ['lubrication']
print(list_dict)

这种写法更高效,找到目标元素后就停止遍历,适合数据量较大的场景。如果不确定目标元素是否存在,可添加默认值避免报错:

r2 = next((p for p in list_dict if p['name'] == 'R2'), None)
if r2:
    r2['hobbies'] = ['lubrication']

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.25 12:45:38