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

Python 3.11:如何在for循环中避免字典键被覆盖?

同类型宝可梦信息追加字典时被覆盖的解决办法

我用Python 3.11编写代码,通过for循环调用PokéAPI获取宝可梦信息,想要将同类型宝可梦的键值对追加到对应字典中,但当前循环会覆盖已有键值,无法实现预期效果,特此寻求解决方案。

原代码

import requests  # 原代码遗漏该导入,需补充

pokelist = ['rattata', 'meowth', 'eevee']

def get_pokemon_by_type(pokemon_list):
    pokedex = {}
    for pokemon_name in pokemon_list:
        url       = f'https://pokeapi.co/api/v2/pokemon/{pokemon_name}'
        response  = requests.get(url)
        weight    = response.json()['weight']
        abilities = []
        for ability in response.json()['abilities']:
            abilities.append(ability['ability']['name'].title())
        for t in response.json()['types']:
            pokedex |= {t['type']['name']: {pokemon_name: {'Abilities': abilities, 'Weight' : weight}}}
    return pokedex
            
get_pokemon_by_type(pokelist)

当前输出

{'normal': {
'eevee':   {'Abilities': ['Run-Away', 'Adaptability', 'Anticipation'], 'Weight': 65}
}
}

期望输出

{'normal': {
'rattata': {'Abilities': ['Run-Away', 'Guts', 'Hustle'],'Weight': 35},
'meowth':  {'Abilities': ['Pickup', 'Technician', 'Unnerve'],'Weight': 42},
'eevee':   {'Abilities': ['Run-Away', 'Adaptability', 'Anticipation'],'Weight': 65}
}
}

解决方案

问题核心是pokedex |= {t['type']['name']: {pokemon_name: ...}}这行代码:每次循环都会直接替换该类型对应的整个字典,而非追加新的宝可梦信息。同时原代码重复调用response.json()会降低效率,建议一次性解析响应数据。

修改后的代码如下:

import requests

pokelist = ['rattata', 'meowth', 'eevee']

def get_pokemon_by_type(pokemon_list):
    pokedex = {}
    for pokemon_name in pokemon_list:
        url = f'https://pokeapi.co/api/v2/pokemon/{pokemon_name}'
        response = requests.get(url)
        data = response.json()  # 一次性解析响应数据
        
        weight = data['weight']
        # 用列表推导式简化abilities的生成
        abilities = [ability['ability']['name'].title() for ability in data['abilities']]
        
        for t in data['types']:
            type_name = t['type']['name']
            # 若类型不存在于pokedex,先初始化空字典
            if type_name not in pokedex:
                pokedex[type_name] = {}
            # 将当前宝可梦信息追加到对应类型的字典中
            pokedex[type_name][pokemon_name] = {
                'Abilities': abilities,
                'Weight': weight
            }
    return pokedex

print(get_pokemon_by_type(pokelist))

关键说明

  1. 避免数据覆盖:先判断类型是否存在,不存在则初始化空字典,再通过pokedex[type_name][pokemon_name]赋值,实现信息追加而非替换。
  2. 性能优化:一次性解析响应数据并复用,避免重复解析带来的资源消耗。
  3. 代码简化:用列表推导式替代原有的循环生成abilities列表,让代码更简洁高效。

内容的提问来源于stack exchange,提问作者Leo Ashcraft

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.21 08:03:38