Te éstas haciendo un lio al iterar sobre la lista y acceder al valor del diccionario usando cada item de la lista como clave, tienes variaas opciones, de peor a mejor, aunque ésto es opinable:
No comprobar si la clave existe previamente
Solo si estás seguro que los items en la lista está siempre en el diccionario, si es el caso, es la forma más simple y eficiente, si no lo puedes asegurar es la peor de todas...
for spell in gandalfspells:
valor = POWER[spell]
listagandalfspells.append(valor)
Usar el operador de pertenencia para saber si la clave existe
for spell in gandalfspells:
if spell in POWER: # La clave existe en el diccionario
valor = POWER[spell]
listagandalfspells.append(valor)
Usar manejo de excepciones
for spell in gandalfspells:
try:
valor = POWER[spell]
except KeyError: # La clave no existe en el diccionario
pass
else:
listagandalfspells.append(valor)
Usar el método dict.get()
for spell in gandalfspells:
valor = POWER.get(spell)
if valor is not None:
listagandalfspells.append(valor)
Python >= 3.8
for spell in gandalfspells:
if (valor:= POWER.get(spell)) is not None:
listagandalfspells.append(valor)
En definitiva, podría ser:
POWER = {
'Fireball': 50,
'Lightning bolt': 40,
'Magic arrow': 10,
'Black Tentacles': 25,
'Contagion': 45
}
gandalf_spells = [
'Fireball', 'Lightning bolt', 'Lightning bolt', 'Magic arrow', 'Fireball',
'Magic arrow', 'Lightning bolt', 'Fireball', 'Fireball', 'Fireball'
]
saruman_spells = [
'Contagion', 'Contagion', 'Black Tentacles', 'Fireball', 'Black Tentacles',
'Lightning bolt', 'Magic arrow', 'Contagion', 'Magic arrow', 'Magic arrow'
]
lista_gandalf_spells = []
for spell in gandalf_spells:
valor = POWER.get(spell)
if valor is not None:
lista_gandalf_spells.append(valor)
lista_saruman_spells = []
for spell in saruman_spells:
valor = POWER.get(spell)
if valor is not None:
lista_saruman_spells.append(valor)
print("Gandalf spells power are", lista_gandalf_spells)
print("Saruman spells power are", lista_saruman_spells)
Gandalf spells power are [50, 40, 40, 10, 50, 10, 40, 50, 50, 50]
Saruman spells power are [45, 45, 25, 50, 25, 40, 10, 45, 10, 10]
Si buscas eficiencia, usar listas por compresión es una buena opción, por ejemplo:
Python >= 3.8
lista_gandalf_spells = [
valor for spell in gandalf_spells if (valor:= POWER.get(spell)) is not None
]
lista_saruman_spells = [
valor for spell in saruman_spells if (valor:= POWER.get(spell)) is not None
]