Search code examples
pythondictionaryunset

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


Solution

  • This is quite fast:

    En_Value = lang['en']
    lang.clear() 
    lang['en'] = En_Value