python - 使用正则表达式在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)
但是,这会返回错误“预期的字符串或类似字节的对象”。
我如何轻松解决这个问题?谢谢
解决方案
如果必须使用正则表达式,可以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)]
推荐阅读
- firebase - 检索文档列表,仅限于数组中的 ID——跟进
- java - 用于获取 OpenCmis 内容的 getContentURL 方法不起作用
- reactjs - TypeError:无法读取未定义的属性“RestaurantID”
- azure - 如何使一个区域中的 Azure 功能与位于其他区域的虚拟机通信?
- css - 不同分辨率css上的div之间的边距相同
- python - while True 和 if 语句打印相同的计算
- unity3d - Unity 2D 和 UI 渲染问题
- if-statement - Hive IF THEN ELSE 用于根据条件执行不同的 Hive 查询
- python - 在安装 pygame 时需要帮助
- r - 在传单地图上添加迷你雷达图作为标记