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