Reputation: 18547
For example given a dictionary
dic={"abcd":2, "abce":2, "abgg":2}
I need to search the dictionary using the prefix of the string, i.e., if given "abc", it will return me two entries
{"abcd":2, "abce":2}
an obvious way:
dic1={}
for k, v in dic.items():
if(k.startswith("abc")):
dic1[k]=v
Is it possible to do it more efficiently?
Upvotes: 0
Views: 391
Reputation: 21506
Try like this,
>>> d={"abcd":2, "abce":2, "abgg":2}
>>> { k:v for k,v in d.iteritems() if k.startswith('abc') }
{'abcd': 2, 'abce': 2}
>>>
Upvotes: 2