lundi 24 avril 2017

How to add specific keys of a dict to another dict if a condition is met?

So, I have a problem where I have to take specific keys and their corresponding values and add them to a new dict if and only if a condition is met. More specifically, I define a function pokemon_by_types(db, types) where it checks if the type of a Pokemon in the given database matches with a type in a list of strings.

The format of the given database is as such:

sample_db = {
"Bulbasaur": (1, "Grass", "Poison", 45, 49, 49, 45, 1, False),
"Charmander": (4, "Fire", None, 39, 52, 43, 65, 1, False),
"Charizard": (6, "Fire", "Flying", 78, 84, 78,100, 1, False),
"Moltres": (146, "Fire", "Flying", 90,100, 90, 90, 1, True),
"Crobat": (169, "Poison", "Flying", 85, 90, 80,130, 2, False),
"Tornadus, (Incarnate Form)": (641, "Flying", None, 79,115, 70,111, 5, True),
"Reshiram": (643, "Dragon", "Fire", 100,120,100, 90, 5, True)
}

As you can see, index 1 and 2 will always be the location for type.

I need to make a function that checks a given dict in the above format and sees if the types (either one, at least one is needed for an if statement to be true) match with the given list of strings "types".

If they do indeed match, I need to add those specific keys and values to an empty dict.

Below is the code I have so far:

def pokemon_by_types(db, types):
    tdb={}
    for pokemon in db:
        if ((db[pokemon])[1]) or ((db[pokemon])[2]) in types:
            tdb.update(db)
    return tdb

Currently, nothin is being added to the dict 'tdb'.

Aucun commentaire:

Enregistrer un commentaire