Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

delete all keys except one in dictionary

I have a dictionary

lang = {'ar':'arabic', 'ur':'urdu','en':'english'} 

What I want to do is to delete all the keys except one key. Suppose I want to save only en here. How can I do it ? (pythonic solution)
What I have tried:

In [18]: for k in lang:    ....:     if k != 'en':    ....:         del lang_name[k]    .... 

Which gave me the run time error:RuntimeError: dictionary changed size during iteration

like image 763
NIlesh Sharma Avatar asked Sep 12 '12 11:09

NIlesh Sharma


People also ask

Can I use Clear () method to delete the dictionary?

Python Dictionary clear()The clear() method removes all items from the dictionary.


2 Answers

Why don't you just create a new one?

lang = {'en': lang['en']} 

Edit: Benchmark between mine and jimifiki's solution:

$ python -m timeit "lang = {'ar':'arabic', 'ur':'urdu','en':'english'}; en_value = lang['en']; lang.clear(); lang['en'] = en_value" 1000000 loops, best of 3: 0.369 usec per loop  $ python -m timeit "lang = {'ar':'arabic', 'ur':'urdu','en':'english'}; lang = {'en': lang['en']}" 1000000 loops, best of 3: 0.319 usec per loop 

Edit 2: jimifiki's pointed out in the comments that my solution keeps the original object unchanged.

like image 70
Fabian Avatar answered Sep 21 '22 09:09

Fabian


This is quite fast:

En_Value = lang['en'] lang.clear()  lang['en'] = En_Value 
like image 42
jimifiki Avatar answered Sep 22 '22 09:09

jimifiki