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

Python中如何根据字典的一个属性值选取另一个属性值

解决方法

你可以通过以下几种方式根据taxonomy的值匹配对应的href:

1. 循环遍历(直观易懂)

逐个检查列表中的每个字典,匹配到目标taxonomy后立即取出href并停止遍历:

target_href = None
for item in term_list:
    if item['taxonomy'] == 'feature':
        target_href = item['href']
        break

如果没有找到匹配项,target_href会保持为None,你可以根据业务需求添加后续判断逻辑。

2. 列表推导式(简洁灵活)

用一行代码生成所有符合条件的href列表,适合存在多个匹配项的场景:

target_hrefs = [item['href'] for item in term_list if item['taxonomy'] == 'feature']
# 若仅需第一个匹配项,先判断列表非空再取值
if target_hrefs:
    target_href = target_hrefs[0]

这种方式会生成完整的匹配结果列表,如果确定只有一个匹配项,也可以直接取索引0,但建议先判断列表是否为空,避免抛出IndexError。

3. 生成器表达式 + next()(高效省内存)

适合仅需第一个匹配项的场景,生成器不会提前创建完整列表,内存占用更低:

target_href = next((item['href'] for item in term_list if item['taxonomy'] == 'feature'), None)

next()会返回第一个匹配的href,第二个参数None是找不到匹配项时的默认返回值,避免抛出StopIteration异常。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.22 20:27:30