unset

delete all keys except one in dictionary

delete all keys except one in dictionary Question: 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 …

Total answers: 4

How can I remove a key from a Python dictionary?

How can I remove a key from a Python dictionary? Question: I want to remove a key from a dictionary if it is present. I currently use this code: if key in my_dict: del my_dict[key] Without the if statement, the code will raise KeyError if the key is not present. How can I handle this …

Total answers: 11