循环字典并使用list的具体值保存键



拥有这个字典和列表:

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

对于上面的例子,我有house_list,12,所以我只想在字典上维护包含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)

提前感谢!

一种方法是使用正则表达式来验证是否且仅当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。

text2int是我从这篇文章中得到的一个函数:是否有一种方法将数字转换为整数?

单行代码是这样的:

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

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

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

相关内容

  • 没有找到相关文章

最新更新