从字典列表提取指定字典的特定值:更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 incategoriesthat contains the 'information' key. If no such dictionary exists, it returnsNoneinstead of throwing aStopIterationerror.- Conditional check for
info_entry: We only attempt to access nested values ifinfo_entryisn'tNone, 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, returningNoneif 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_roleswill beNone. - 'information' exists but is
None:emc_roleswill beNone. - 'emcRoles' is missing from 'information':
emc_roleswill beNone.
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
相关产品推荐
相关产品推荐

