【问题标题】:How to add specific keys of a dict to another dict if a condition is met?如果满足条件,如何将字典的特定键添加到另一个字典?
【发布时间】:2017-09-21 18:46:03
【问题描述】:

所以,我有一个问题,当且仅当满足条件时,我必须获取特定的键及其对应的值并将它们添加到新的 dict 中。更具体地说,我定义了一个函数pokemon_by_types(db, types),它检查给定数据库中口袋妖怪的类型是否与字符串list 中的类型匹配。

给定数据库的格式如下:

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 语句为真)与给定的字符串“类型”列表匹配.

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

下面是我目前的代码:

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

目前,没有向字典“tdb”添加任何内容。

【问题讨论】:

  • 您的情况没有按照您的想法进行,您的意思是if db[pokemon][1] in types or db[pokemon][2] in types: 另外,您不想使用db 进行更新,因为这会更新*整个字典。你可以做tbd[pokemon] = db[pokemon]
  • 你怎么称呼你的方法?
  • @Robert Seaman 我正在使用单独的测试器文件调用函数。 Juanpa.arrivillaga:谢谢,这是有道理的!

标签: python csv dictionary if-statement key


【解决方案1】:

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

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 中。

【讨论】:

  • 你真的应该花时间解释为什么 OP 方法是错误的,而不是在他们身上倾倒一个单行字。
猜你喜欢
  • 1970-01-01
  • 2020-10-14
  • 1970-01-01
  • 2016-02-03
  • 2012-12-25
  • 1970-01-01
  • 2011-03-10
  • 2018-07-27
相关资源
最近更新 更多