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]
>>> [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])
>>> 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]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With