python3删除字典中空值的键值对

python版本

python 3.8.2

操作步骤

In [1]: AAA = {'A': 1, 'B': '', 'C': 3, 'D': ''}                                                                                                                                                                  

In [2]: for key in list(AAA.keys()):       // 注意这里需要添加list(),不然会报错;python2环境下,可以不加list(),因为python2下的dict.keys()返回的就是列表
   ...:     if not AAA.get(key): 
   ...:         del AAA[key] 
   ...:                                                                                                                                                                                                           

In [3]: print(AAA)                                                                                                                                                                                                
{'A': 1, 'C': 3}

  

原文地址:https://www.cnblogs.com/ding2016/p/14317710.html