如果满足条件,如何将dict的特定键添加到另一dict?

2024-04-28 23:28:05 发布

您现在位置:Python中文网/ 问答频道 /正文

所以,我有一个问题,我必须采取具体的键和他们相应的值,并添加到一个新的dict当且仅当一个条件得到满足。更具体地说,我定义了一个函数pokemon_by_types(db, types),用于检查给定数据库中Pokemon的类型是否与字符串列表中的类型匹配。你知道吗

给定数据库的格式如下:

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)
}

如您所见,索引1和索引2将始终是类型的位置。你知道吗

我需要做一个函数,用上面的格式检查给定的dict,看看类型(其中一个,if语句至少需要一个)是否与给定的字符串列表“types”匹配。你知道吗

如果它们确实匹配,我需要将这些特定的键和值添加到一个空的dict中

以下是我目前掌握的代码:

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

目前,没有任何内容被添加到dict“tdb”中。你知道吗


Tags: 函数字符串数据库falsetrue类型列表db
1条回答
网友
1楼 · 发布于 2024-04-28 23:28:05

您可以使用dict理解来获取您要查找的项目:

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

你的例子有一个问题:if ((db[pokemon])[1]) or ((db[pokemon])[2]) in types:

这就是说,如果((db[pokemon])[1])返回True或者((db[pokemon])[2])types中。你知道吗

必须指定每个条件:if db[pokemon][1] in types or db[pokemon][2] in types:

另一个问题是tdb.update(db)。如果if语句的计算结果为True,那么实际上会将所有元素添加到tdb中。你知道吗

相关问题 更多 >