I have a list as such:
pokemonList = ['Ivysaur', 'Grass', 'Poison', '', 'Venusaur', 'Grass', 'Poison', '', 'Charmander', 'Fire', ''...]
Note that the pattern is 'Pokemon name', 'its type', ''...next pokemon
Pokemon come in both single and dual type forms. How can I code this so that every pokemon (key) will have their respective type(s) applied as its value?
What I've got so far:
types = ("", "Grass", "Poison", "Fire", "Flying", "Water", "Bug","Dark","Fighting", "Normal","Ground","Ghost","Steel","Electric","Psychic","Ice","Dragon","Fairy")
pokeDict = {}
for pokemon in pokemonList:
if pokemon not in types:
#the item is a pokemon, append it as a key
else:
for types in pokemonList:
#add the type(s) as a value to the pokemon
The proper dictionary will look like this:
{Ivysaur: ['Grass', 'Poison'], Venusaur['Grass','Poison'], Charmander:['Fire']}
Just iterate the list and construct the item for the dict appropriately..
current_poke = None
for item in pokemonList:
if not current_poke:
current_poke = (item, [])
elif item:
current_poke[1].append(item)
else:
name, types = current_poke
pokeDict[name] = types
current_poke = None
Recursive function to slice up the original list, and a dictionary comprehension to create the dict:
# Slice up into pokemon, subsequent types
def pokeSlice(pl):
for i,p in enumerate(pl):
if not p:
return [pl[:i]] + pokeSlice(pl[i+1:])
return []
# Returns: [['Ivysaur', 'Grass', 'Poison'], ['Venusaur', 'Grass', 'Poison'], ['Charmander', 'Fire']]
# Build the dictionary of
pokeDict = {x[0]: x[1:] for x in pokeSlice(pokemonList)}
# Returning: {'Charmander': ['Fire'], 'Ivysaur': ['Grass', 'Poison'], 'Venusaur': ['Grass', 'Poison']}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With