首页 > 解决方案 > 使用正则表达式在python字典中查找键

问题描述

和你一样,我有一本字典街道名称及其值。键是字符串,值是整数。我想编写一小段代码,允许我使用正则表达式打印所有以“gatan”结尾的街道名称。

dictionary = {Storgatan: 46, Talgvägen: 51, Malmstigen: 8, Huvudgatan: 3...}

import re 

ends_with= 'gatan$'
test_dictionary= dictionary 

m1 = re.match(ends_with,test_dictionary)
if m1 is not None:
    print(m1)

但是,这会返回错误“预期的字符串或类似字节的对象”。

我如何轻松解决这个问题?谢谢

标签: pythonregex

解决方案


如果必须使用正则表达式,可以re.match在遍历字典时使用。

import re

dictionary = {'Storgatan': 46, 'Talgvägen': 51, 'Malmstigen': 8, 'Huvudgatan': 3}

regex = '.*gatan$'

results = [v for k, v in dictionary.items() if re.match(regex, k)]

print(results)

输出:

[46, 3]

注意:这对于大型词典来说会很慢

如果您只想要键名:

matching_keys = [k for k in dictionary if re.match(regex, k)]

推荐阅读