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".

沒有留言:

張貼留言

[Git 常見問題] error: The following untracked working tree files would be overwritten by merge

  Source From  Here 方案1: // x -----删除忽略文件已经对 git 来说不识别的文件 // d -----删除未被添加到 git 的路径中的文件 // f -----强制运行 #   git clean -d -fx 方案2: 今天在服务器上  gi...