Reputation: 13
Suppose I am given:
{"abc":2, "abcde":3, "aeg":1}
and a prefix in a function prefixsearch(dictionary, prefix)
.
I need to search the dictionary using the prefix, i.e., "ab" will return me two entries
{"abc":2, "abcde":3}
I am struggling to code this using a normal for loop. Any help is appreciated
Upvotes: 0
Views: 1242
Reputation: 88236
You can use a dictionary comprehension with str.startswith
:
def prefixsearch(dictionary, prefix):
return {k:v for k,v in dictionary.items() if k.startswith(prefix)}
d = {"abc":2, "abcde":3, "aeg":1}
prefixsearch(d, 'ab')
#{'abc': 2, 'abcde': 3}
Which would be equivalent to the following for loop:
def prefixsearch(dictionary, prefix):
out = {}
for k,v in dictionary.items():
if k.startswith(prefix):
out[k] = v
return out
Upvotes: 4