Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting a list into a multi-valued dict

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']}
like image 464
avereux Avatar asked Mar 15 '23 06:03

avereux


2 Answers

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
like image 143
Chad S. Avatar answered Mar 25 '23 08:03

Chad S.


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']}
like image 37
leroyJr Avatar answered Mar 25 '23 10:03

leroyJr