2017-06-21 102 views
1

我有以下词典在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"

+4

你尝试过这么远吗? –

+0

@KevinMGranger手动搜索,就像我用small_dict一样。 – ShanZhengYang

+0

你已经演示了如何筛选基于一个布尔条件的字典,并从你可以很容易地修改它使用正则表达式来代替。 –

回答

1

这应该与你的榜样所有的按键,以及您的例外情况:

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

它使用与您的例外一个新的例子字典:

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

您可以使用正则表达式匹配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"]} 
+0

最后一行是我所困惑的。这次真是万分感谢! – ShanZhengYang

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}