【问题标题】:Looping a dictionary and keep keys with a concrete value of list循环字典并使用列表的具体值保留键
【发布时间】:2021-12-03 14:51:23
【问题描述】:

拥有这本词典和列表:

input_list = {"This_is_House1_Test1": "one", "Also_House2_Mother": "two", "Fefe_House3_Father": "three"}
house_list = [1, 2]

对于上面的示例,我有house_list12,所以我只想在字典中保留包含House1House2 的键,并删除其余的。

我想要的上述简化输入的输出是:

{"This_is_House1_Test1": "one", "Also_House2_Mother": "two"}

这是我没有运气的尝试:

for key in list(input_list.keys()):
    for house_id in house_list:
        if "House" + str(house_id) not in key:
                input_list.pop(key)

提前致谢!

【问题讨论】:

  • HouseN 是否总是被下划线包围?
  • 如果你有一个带“House13”的钥匙,那会怎样?
  • 并非总是如此,@jarmod
  • 不,@DaniMesejo,只是House1Houuse2。在house_list = [1, 2, 13]的情况下应该包含它。
  • 与@eh329 的回答有关,input_list 中的值(例如“one”、“two”)始终保证是键中门牌号的英文表示(例如 1 表示House1, 2 for House2)?

标签: python arrays dictionary


【解决方案1】:

一种方法是使用正则表达式来验证是否且仅当house_list 中的值之一在input_list 中:

import re

input_list = {"This_is_House1_Test1": "one", "Also_House2_Mother": "two",
              "Fefe_House3_Father": "three", "Fefe_House13_Father": "three",
              "Fefe_House14_Father": "three", "Fefe_House24_Father": "three"}

house_list = [1, 2, 13]

house_numbers = "|".join(f"{i}" for i in sorted(house_list, reverse=True))
pat = re.compile(rf"""(House{house_numbers})  # the house patterns
                      \D # not another digit""", re.VERBOSE)

res = {key: value for key, value in input_list.items() if pat.search(key)}
print(res)

输出

{'This_is_House1_Test1': 'one', 'Also_House2_Mother': 'two', 'Fefe_House13_Father': 'three'}

可以看出只有 1、2、13 匹配,而不是 3、14、24。

【讨论】:

  • 这不也(错误地)包括This_is_House111111_Test1吗?
  • @jarmod 正确,更新了答案
  • 不确定是否能解决问题。
  • 因为“House1”在“House111111”中。将以下内容添加到测试数组中:"aaa_House11111_aaa": "zero" 查看此内容。
【解决方案2】:

text2int 是我从这篇文章中得到的一个函数: Is there a way to convert number words to Integers?

一个班轮是这样的:

{k:v for k, v in input_list.items() if text2int(v) in house_list}

【讨论】:

  • 我确实做到了。你认为我为什么发布它?
  • 嗯,这实际上是一种有趣的方法。 OP没有说明这一点,但让我们看看dict值是否保证是门牌号的英文文本。
  • 我在运行 dict 理解后运行了 for 循环。我认为这就是我没有看到错误的原因。
【解决方案3】:

您可以使用正则表达式匹配从文本中提取最大门牌号,如下:

import re

input_list = {
    "This_is_House1_Test1": "one",
    "aaa_House11111_aaa": "xxx",
    "Also_House2_Mother": "two",
    "Fefe_House3_Father": "three"
}

house_list = [1, 2]

keys = []
items = {}

for key in input_list.keys():
    result = re.search(r'House(\d+)', key)
    if result and int(result.group(1)) in house_list:
        keys.append(key)
        items[key] = input_list[key]

print("Keys:", keys)
print("Items:", items)

输出是:

Keys: ['This_is_House1_Test1', 'Also_House2_Mother']
Items: {'This_is_House1_Test1': 'one', 'Also_House2_Mother': 'two'}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-08-09
    • 2014-09-04
    • 2020-04-28
    • 2021-07-27
    • 1970-01-01
    • 2021-03-24
    • 2018-04-18
    相关资源
    最近更新 更多