delete all keys except one in dictionary

拈花ヽ惹草 提交于 2020-06-24 20:31:15

问题


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


回答1:


This is quite fast:

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



回答2:


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.




回答3:


Iterate over keys() instead:

for k in lang.keys():
    if k != 'en':
        del lang_name[k]

If you're using Python 3 I believe you need to use list(lang.keys()) instead.




回答4:


pop() it via for loop like this

[s.pop(k) for k in list(s.keys()) if k != 'en']


来源:https://stackoverflow.com/questions/12387575/delete-all-keys-except-one-in-dictionary

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!