gpt4 book ai didi

python - 删除基于正则表达式的字典值?

转载 作者:行者123 更新时间:2023-11-28 22:26:35 25 4
gpt4 key购买 nike

我在 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"]}

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

单独的问题:如果有特殊的异常(exception)怎么办,例如我想输入一个名为 "helloXX" 的键?

最佳答案

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

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}

关于python - 删除基于正则表达式的字典值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44682195/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com