使用正则表达式在python字典中查找键
我有一本字典街道名称和它们的值,就像你一样。键是字符串,值是整数。 我想写一小段代码,允许我使用正则表达式打印所有以“gatan”结尾的街道名称使用正则表达式在python字典中查找键,python,regex,Python,Regex,我有一本字典街道名称和它们的值,就像你一样。键是字符串,值是整数。 我想写一小段代码,允许我使用正则表达式打印所有以“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_dictiona
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)
但是,这将返回错误“预期的字符串或字节类对象”
如何轻松解决此问题?谢谢简单地说,我们可以像这样使用
key.endswith('gatan')
:
for key, val in dictionary.items():
if isinstance(key, str) and not key.endswith('gatan'):
# key not ending with `gatan`
print(key, val)
filtered_dictionary = {key: val for key, val in dictionary.items() if not key.endswith('gatan')}
如果您想创建另一个字典,那么我们可以在一行中完成,如下所示:
for key, val in dictionary.items():
if isinstance(key, str) and not key.endswith('gatan'):
# key not ending with `gatan`
print(key, val)
filtered_dictionary = {key: val for key, val in dictionary.items() if not key.endswith('gatan')}
请看一下正则表达式的文档。查找
匹配
函数定义。您将看到函数需要一个字符串
数据结构,而不是dict
如果必须使用正则表达式,可以在迭代字典时使用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)]
有点不清楚,定义“减去”所有街道名称的含义还请注意
re.match
和re.search
之间的区别match
仅在字符串开头检查匹配项。@duvet我也将其添加到了我的答案中。您是否尝试过这个matching_keys=[k代表字典中的k如果re.match(regex,k)]
您确定您正在执行打印(匹配_keys)
而不是print(结果)
?