如何从嵌套字典列表中获取type为web的字典的id值?
查找包含指定type的字典并返回对应id值
问题场景
你拥有一个嵌套字典,其中accounts键对应一个字典列表——列表长度可能为0或任意数量,列表内的字典键通常一致但值不同。需要找到其中type值为web的字典,若存在则返回其id值;若不存在则返回默认值(比如None)。
示例数据
data = {'accounts': [{'id': 'test#11882', 'name': 'test#11882', 'type': 'net', 'verified': False}, {'id': '99999', 'name': 'test999', 'type': 'web', 'verified': False}]}
解决方案
方法1:基础遍历法(直观易懂)
通过遍历accounts列表,逐个检查字典的type值,找到匹配项后立即返回id,避免不必要的遍历:
target_id = None for account in data['accounts']: # 使用get()避免因字典缺少'type'键抛出KeyError if account.get('type') == 'web': target_id = account['id'] break # 找到第一个匹配项就停止遍历,提升效率 print(target_id) # 输出:99999
方法2:生成器表达式+next()(简洁高效)
用生成器表达式配合next()函数,一行代码完成查找,同时指定找不到时的默认值:
# 生成器遍历符合条件的字典,next()返回第一个匹配的id,无匹配则返回None target_id = next((acc['id'] for acc in data['accounts'] if acc.get('type') == 'web'), None) print(target_id) # 输出:99999
关键注意点
- 使用
account.get('type')而非直接account['type']:防止部分字典缺失type键时触发KeyError - 优先返回第一个匹配项:如果列表中有多个
type: web的字典,上述方法只会返回第一个的id,若需要所有匹配项,可改用列表推导式收集结果 - 空列表/无匹配处理:当
accounts为空或没有符合条件的字典时,target_id会被设为None,你可以根据需求替换为其他默认值(比如空字符串'')
内容的提问来源于stack exchange,提问作者Jared Robertson
相关产品推荐
相关产品推荐

