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

从字典列表提取指定字典的特定值:更Pythonic且空安全的实现

Pythonic Way to Safely Retrieve information.emcRoles

Here's a concise, safe approach that avoids messy nested loops and handles all edge cases (like missing 'information' key, 'information' having a None value, or 'emcRoles' being absent entirely):

categories = [
    {'summarycategory': {'amount':1233}}, 
    {'hhCategory': {}}, 
    {'information': {'mRoles': ['4456'], 'cRoles': None, 'emcRoles': ['spm/4456']}}
]

# Find the first item with the 'information' key (returns None if not found)
info_entry = next((item for item in categories if 'information' in item), None)

# Safely extract emcRoles, handling missing keys or null values
emc_roles = info_entry.get('information', {}).get('emcRoles', None) if info_entry is not None else None

print(emc_roles)  # Output: ['spm/4456']

Breakdown of the Approach:

  • next(..., None): This efficiently finds the first dictionary in categories that contains the 'information' key. If no such dictionary exists, it returns None instead of throwing a StopIteration error.
  • Conditional check for info_entry: We only attempt to access nested values if info_entry isn't None, preventing AttributeErrors from popping up.
  • Chained get() calls:
    • info_entry.get('information', {}) retrieves the value of 'information'; if the key is missing, it uses an empty dictionary as a fallback.
    • .get('emcRoles', None) then pulls the 'emcRoles' value from that result, returning None if the key doesn't exist.

Even More Concise (Python 3.8+):

If you're using Python 3.8 or newer, you can use the walrus operator (:=) to condense the logic into a single line:

emc_roles = (info_entry.get('information', {}).get('emcRoles', None) 
             if (info_entry := next((item for item in categories if 'information' in item), None)) 
             else None)

Edge Case Validation:

This solution works reliably for all tricky scenarios:

  • No 'information' key: emc_roles will be None.
  • 'information' exists but is None: emc_roles will be None.
  • 'emcRoles' is missing from 'information': emc_roles will be None.

It’s clean, readable, and aligns with Python’s "explicit is better than implicit" philosophy while keeping your code concise.

内容的提问来源于stack exchange,提问作者More Than Five

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.20 11:41:43