Stella
Stella

Reputation: 1564

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]

Upvotes: 4

Views: 4406

Answers (3)

Balkishan Mer
Balkishan Mer

Reputation: 134

I tried below hope it help you, by getting the keys of dictionary and then if the first index of the key is your start with character then extend the list with the key dictionary list.

n='s' # your start with character
result=[] # your output

for d in dict1.keys():
    if n == d[0]:
        result.extend(dict1[d])

print result

Upvotes: 3

Tim Pietzcker
Tim Pietzcker

Reputation: 336128

>>> [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])

Upvotes: 7

Ashwini Chaudhary
Ashwini Chaudhary

Reputation: 250941

>>> 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]

Upvotes: 3

Related Questions