程式扎記: [ Python 常見問題 ] How to remove a key from a python dictionary?

標籤

2016年10月13日 星期四

[ Python 常見問題 ] How to remove a key from a python dictionary?

Source From Here 
Quesiton 
When trying to delete a key from a dictionary, I write: 
  1. if 'key' in myDict:  
  2.     del myDict['key']  
Is there a one line way of doing this? 

How-To 
Use dict.pop()
>>> my_dict = {"last":"john", "first":"lee", "age":18, }
>>> my_dict.pop("last")
'john'
>>> my_dict.pop("not exist")
Traceback (most recent call last):
File "", line 1, in

KeyError: 'not exist'
>>> my_dict.pop("middle", "KC") # Second argument 'KC' is returned while the key doesn't exist
'KC'
>>> my_dict
{'age': 18, 'first': 'lee'}

For more usage of dict, please refer to "[Quick Python] 7. Dictionaries".

沒有留言:

張貼留言

網誌存檔

關於我自己

我的相片
Where there is a will, there is a way!