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

如何遍历含未知数量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 foo is invalid (you can't assign a generator expression like that in a single line).
  • Even if you fixed the loop structure, f would be the key string (e.g., 'A292340'), and strings don't have a values() 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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.22 08:54:17