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 that the key with 's' has? eg dict1['s*'] to get the result dict1['s*']=[1,2,3,4,5,6,10,11]

+4
source share
3 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 should be a regular expression

 >>> 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 see here is a nested understanding. It is equivalent

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

As such, it is a bit inefficient because the regex is checked too often (and the elements are added one by one). So another solution would be

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

I tried below, I hope this helps you by getting dictionary keys, and then if the first key index is your start with a symbol, then expand the list with a list of keywords.

 n='s' # your start with character result=[] # your output for d in dict1.keys(): if n == d[0]: result.extend(dict1[d]) print result 
+3
source
 >>> 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 the 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] 
+2
source

Source: https://habr.com/ru/post/1495078/


All Articles