根据正则表达式删除字典值?

时间:2017-06-21 17:04:28

标签: python regex string dictionary

我在Python中有以下字典

dict1 = {"key1": 2345, "key2": 356, "key3": 773, "key44": 88, "key333": 12, "key3X": 13}

我想删除不遵循模式"xxx#""xxx##"的密钥。也就是说,三个字符后跟一位整数或两位整数。使用上面的例子,这是:

new_dict = {"key1": 2345, "key2": 356, "key3": 773, "key44": 88}

对于一个或两个键,我创建一个新词典的方式是列表理解:

small_dict = {k:v for k,v in your_dic.items() if v not in ["key333", "key3X"]}

但是,我如何使用正则表达式/其他字符串方法删除这些字符串?

单独的问题:如果有特殊例外情况,例如我要键入的一个键叫"helloXX"

3 个答案:

答案 0 :(得分:2)

您可以使用正则表达式匹配3个字母,后跟一个或两个数字,然后直接跟在字符串的末尾($):

>>> import re
>>> small_dict = {k:v for k,v in dict1.items() if re.match('[a-z]{3}\d{1,2}$',k, re.IGNORECASE)}
>>> small_dict
{'key44': 88, 'key3': 773, 'key1': 2345, 'key2': 356}

请注意,re.match会在字符串开头搜索正则表达式:"123key123"例如不会匹配。

如果有例外,您可以在过滤密钥后添加它们。 如果你想一气呵成:

small_dict = {k:v for k,v in dict1.items() if re.match('[a-z]{3}\d{1,2}$',k, re.IGNORECASE) or k in ["hello12", "hello34"]}

答案 1 :(得分:1)

这应该匹配示例中的所有键以及例外情况:

new_dict = {k:dict1[k] for k in dict1 if re.match('[^\d\s]+\d{1,2}$', k)}

使用带有异常的新示例dict:

>>> dict1 = {"key1": 2345, "key2": 356, "key3": 773, "key44": 88, "key333": 12, "key3X": 13, "hello13": 435, "hello4325": 345, "3hi33":3}
>>> new_dict = {k:dict1[k] for k in dict1 if re.match('[^\d\s]+\d{1,2}$', k)}
>>> print(new_dict)
{'hello13': 435, 'key44': 88, 'key3': 773, 'key2': 356, 'key1': 2345}

答案 2 :(得分:1)

另一种变化:

import re

dict1 = {"key1": 2345, "key2": 356, "key3": 773, "key44": 88, "key333": 12, "key3X": 13}

rx = re.compile(r'^[A-Za-z]{3}\d{1,2}$')

new_dict = {key: dict1[key] for key in dict1 if rx.search(key)}
print(new_dict)
# {'key44': 88, 'key3': 773, 'key1': 2345, 'key2': 356}
相关问题