避免在for循环中覆盖字典键。

huangapple go评论66阅读模式
英文:

Python: Avoid overwriting dictionary keys in a for loop

问题

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

Python 3.11

I'm not sure if I'm needing to individually create the dictionaries and merge them together? But using the for loop, I'm not able to figure out how to avoid overwriting the first key. I'm wanting to append an additional key:value pair.

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)

Current output:

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

Expected output:

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

答案1

得分: 3

你不想将新的 dictpokedex 合并,而是想将当前Pokemon的名称映射到新的 dict

在你现有的代码中,你用一个全新的 dict 替换了与名称 normal 映射的旧 dict,而不是更新已有的 normal dict

英文:

You don't want to union the new dict with pokedex; you want to map the name of the current Pokemon to the new dict.

pokedex.setdefault(t['type']['name'], {})[pokemon_name] = {'Abilities': abilities, 'Weight' : weight}}

In your current code, you replace one dict mapped to the name normal with a completely new dict that also has the key normal, rather than updating the existing normal dict.

huangapple
  • 本文由 发表于 2023年5月22日 22:35:01
  • 转载请务必保留本文链接:https://go.coder-hub.com/76307277.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定