delete all keys except one in dictionary

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’]}” … Read more

Unset readonly variable in bash

Actually, you can unset a readonly variable. but I must warn that this is a hacky method. Adding this answer, only as information, not as a recommendation. Use it at your own risk. Tested on ubuntu 13.04, bash 4.2.45. This method involves knowing a bit of bash source code & it’s inherited from this answer. … Read more

How can I remove a key from a Python dictionary?

To delete a key regardless of whether it is in the dictionary, use the two-argument form of dict.pop(): my_dict.pop(‘key’, None) This will return my_dict[key] if key exists in the dictionary, and None otherwise. If the second parameter is not specified (i.e. my_dict.pop(‘key’)) and key does not exist, a KeyError is raised. To delete a key … Read more