英文:
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
你不想将新的 dict
与 pokedex
合并,而是想将当前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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论