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

如何基于指定name值访问字典列表中的href属性?

解决字典列表中按name值获取对应href的问题

你遇到的TypeError是因为details是列表类型,列表只能用整数或切片作为索引,不能直接用字符串'name'来访问。要实现按name值获取对应的href,有以下几种可行方式:

1. 基础循环遍历

逐个检查列表中的每个字典,匹配到目标name后取出href:

details = [{'name': 'veeresh', 'href': 'www.google.com', 'id': '12345'}, {'name': 'Chandan', 'href': 'www.facebook.com', 'id': '67895'}]

target_name = 'veeresh'
target_href = None
for item in details:
    if item['name'] == target_name:
        target_href = item['href']
        break

print(target_href)  # 输出: www.google.com

这种方式逻辑直观,适合简单场景,还能处理找不到匹配项的情况(此时target_href保持None)。

2. 用next()函数简化查询

通过生成器表达式配合next(),可以一行完成查询,还能设置默认值避免找不到时抛出StopIteration错误:

details = [{'name': 'veeresh', 'href': 'www.google.com', 'id': '12345'}, {'name': 'Chandan', 'href': 'www.facebook.com', 'id': '67895'}]

target_name = 'Chandan'
target_href = next((item['href'] for item in details if item['name'] == target_name), None)

print(target_href)  # 输出: www.facebook.com

如果不需要处理默认值,也可以省略第二个参数,但找不到匹配项时会报错。

3. 预先构建映射字典(适合多次查询)

如果需要频繁按name查询href,先把列表转换成以name为键、href为值的字典,后续查询会更高效:

details = [{'name': 'veeresh', 'href': 'www.google.com', 'id': '12345'}, {'name': 'Chandan', 'href': 'www.facebook.com', 'id': '67895'}]

# 构建name到href的映射
name_href_map = {item['name']: item['href'] for item in details}

# 直接通过name取值
print(name_href_map['veeresh'])  # 输出: www.google.com
print(name_href_map['Chandan'])  # 输出: www.facebook.com

注意:如果列表中有多个字典的name值重复,后面的会覆盖前面的,所以要确保name值唯一时再用这种方法。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.19 13:02:11