Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to get dict value by regex in python

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]

like image 480
Stella Avatar asked Dec 12 '22 12:12

Stella


2 Answers

>>> [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])
like image 178
Tim Pietzcker Avatar answered Dec 15 '22 00:12

Tim Pietzcker


>>> import re
>>> from itertools import chain
def natural_sort(l): 
     # http://stackoverflow.com/a/4836734/846892
     convert = lambda text: int(text) if text.isdigit() else text.lower() 
     alphanum_key = lambda key: [ convert(c) for c in re.split('([0-9]+)', key) ] 
     return sorted(l, key = alphanum_key)
... 

Using glob pattern, 's*':

>>> import fnmatch
def solve(patt):
    keys = natural_sort(k for k in dict1 if fnmatch.fnmatch(k, patt))
    return list(chain.from_iterable(dict1[k] for k in keys))
... 
>>> solve('s*')
[1, 2, 3, 4, 5, 6, 10, 11]

Using regex:

def solve(patt):
    keys = natural_sort(k for k in dict1 if re.search(patt, k))
    return list(chain.from_iterable( dict1[k] for k in keys ))
... 
>>> solve('^s')
[1, 2, 3, 4, 5, 6, 10, 11]
like image 44
Ashwini Chaudhary Avatar answered Dec 15 '22 00:12

Ashwini Chaudhary