how to get dict value by regex in python

dictionary, python, regex

Solution

>>> [x for d in dict1 for x in dict1[d] if d.startswith("s")]
[1, 2, 3, 4, 5, 6, 10, 11]

or, if it needs to be a regex

>>> regex = re.compile("^s")
>>> [x for d in dict1 for x in dict1[d] if regex.search(d)]
[1, 2, 3, 4, 5, 6, 10, 11]

What you're seeing here is a nested list comprehension. It's equivalent to

result = []
for d in dict1:
    for x in dict1[d]:
        if regex.search(d):
            result.append(x)

As such, it's a little inefficient because the regex is tested way too often (and the elements are appended one by one). So another solution would be

result = []
for d in dict1:
    if regex.search(d):
       result.extend(dict1[d])

Problem

``` dict1={'s1':[1,2,3],'s2':[4,5,6],'a':[7,8,9],'s3':[10,11]} ``` how can I get all the value which key is with 's'? like `dict1['s*']`to get the result is `dict1['s*']=[1,2,3,4,5,6,10,11]`

Original source

Related problems