Efficient way of removing keys of certain prefix from python dictionary -


i have python dictionary looks this;

{'prefix_1':'12', 'prefix_2':'11', 'prefix_3':'14', '1':'241', '2':'312', '3':'421' } 

i want remove key-value pairs of keys start 'prefix'. result should dictionary this;

{'1':'241', '2':'312', '3':'421' } 

my current way of doing remove each pair 1 one using del dictionary['prefix_x']. more efficient ways of doing so?

i using python 2.7

since other answers use dict comprehension create new dict , leave original dict untouched, i'll give 1 change dict in place:

for k in d.keys():     if k.startswith('prefix'):         d.pop(k) 

is there better way?

let's there n keys in dictionary, find keys given prefix, you'll have iterate on keys, , of o(n) time complexity.

then you'll need delete them 1 one, in worst case of them given prefix, of o(n) time complexity.

the total time complexity if o(n).


Comments

Popular posts from this blog

angularjs - ADAL JS Angular- WebAPI add a new role claim to the token -

php - CakePHP HttpSockets send array of paramms -

node.js - Using Node without global install -