如何遍历含未知数量A开头键的嵌套字典,获取对应comp值?
Solution to Iterate Over "A"-Starting Keys in Your Dictionary
First, let's break down why your initial attempt didn't work:
- The syntax
foo = data.keys() for f in foois invalid (you can't assign a generator expression like that in a single line). - Even if you fixed the loop structure,
fwould be the key string (e.g., 'A292340'), and strings don't have avalues()method—you need to access the corresponding value from the original dictionary instead.
Here are a few straightforward, reliable ways to solve this:
Method 1: Loop Through Keys and Filter
Iterate over all keys in your dictionary, check if they start with "A", then retrieve the associated value:
data = {'A292340': {'comp': 'company_value1'}, 'B12345': {'comp': 'other_company'}, 'A196030': {'comp': 'company_value2'}} for key in data.keys(): if key.startswith('A'): # Get the inner dictionary and extract the 'comp' value company_value = data[key]['comp'] print(f"Key: {key}, Company Value: {company_value}")
Method 2: Use items() for Direct Key-Value Access
This approach is more concise since you get both the key and its value in one step, avoiding an extra lookup:
for key, value in data.items(): if key.startswith('A'): # 'value' is the inner dict, so we can directly access 'comp' print(f"Key: {key}, Company Value: {value['comp']}")
Method 3: Collect Values with a List Comprehension
If you want to gather all the 'comp' values into a list instead of printing them immediately:
company_values = [value['comp'] for key, value in data.items() if key.startswith('A')] print(company_values) # Output: ['company_value1', 'company_value2']
All these methods work regardless of how many "A"-starting keys you have, and you don't need to know their exact names beforehand.
内容的提问来源于stack exchange,提问作者Hannah Lee
相关产品推荐
相关产品推荐

