Python 在字典中查找键并将键的一部分用作变量
假设我在字典中有一组键:Python 在字典中查找键并将键的一部分用作变量,python,regex,dictionary,Python,Regex,Dictionary,假设我在字典中有一组键: dictionary=({"key[0]":1, "bar[0]":1, "key[2]":2, "key[4]":3, "foo[1]":3, "bar[3]":2, "dummy":42}) 我想搜索所有与regex patternkey\[([0-9]+)\]匹配的键,并处理它们以捕获键中的第一个(也是唯一一个)regex模
dictionary=({"key[0]":1, "bar[0]":1, "key[2]":2, "key[4]":3, "foo[1]":3, "bar[3]":2, "dummy":42})
我想搜索所有与regex patternkey\[([0-9]+)\]
匹配的键,并处理它们以捕获键中的第一个(也是唯一一个)regex模式组。
换句话说,我只想选择键“key[someIntValue]”
,并对它们执行操作,同时将someIntValue值作为变量提供(或者以某种方式引用)
使用我想表达的伪代码:
for <all the keys matching "key[someIntValue]"> in dictionary
function(someIntValue)
字典中的
函数(someIntValue)
我需要使用正则表达式还是有其他方法?对于这样的问题,最好的代码解决方案是什么?Python 2和Python 3的答案是否不同?您可以使用以下正则表达式和适当的捕获组:
import re
pat = re.compile("^key\[(\d+)\]$") # \d+: one or more digits, (): capt. group
for k, v in dictionary.items():
m = pat.match(k)
if m:
i = int(m.group(1)) # this is someIntValue
# do stuff with i, k, v
由于键应该始终完全相同,因此可以比较字符串而不是使用正则表达式
dictionary={“key[0]”:1,“bar[0]”:1,“key[2]”:2,“key[4]”:3,“foo[1]”:3,“bar[3]”:2,“dummy”:42}
对于dictionary.keys()中的键:
如果键[:4]=“键[”和键[-1]=“键]”以及键[4:-1]。isdigit():
keydigit=int(键[4:-1])
打印(关键数字)
您可以使用dict comprehension制作一本新字典,如果键与您的模式匹配,它会将键映射到其中的数字:
import re
pattern = "^key\[(\d+)\]$"
matches = [re.search(pattern, key) for key in dictionary.keys()]
new_dictionary = {match.group(0): int(match.group(1)) for match in matches if match is not None}
请注意,match.group(0)
是键,match.group(1)
是数字。还要注意,如果与您的模式不匹配,则match
为none
上面将返回一个新字典,如果键符合您的规范,它将键映射到它们的整数值。在您的示例中,它返回{'key[0]':0,'key[2]':2,'key[4]':4}
。现在你可以做了
for key, digit in new_dictionary.items():
...