william007
william007

Reputation: 18547

Searching dictionary using prefixes

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

Answers (1)

Adem Öztaş
Adem Öztaş

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

Related Questions