python字典去除空值
时间: 2024-05-11 12:13:02 浏览: 201
Python去掉字符串中空格的方法
5星 · 资源好评率100%
在Python中,可以使用字典推导式和内置函数来去除字典中的空值(None、空字符串和空列表等)。具体实现方法如下:
1. 字典推导式
```python
original_dict = {"a": 1, "b": None, "c": "", "d": []}
new_dict = {k: v for k, v in original_dict.items() if v is not None and v != "" and v != []}
print(new_dict)
# 输出:{"a": 1}
```
2. 内置函数filter()配合lambda表达式
```python
original_dict = {"a": 1, "b": None, "c": "", "d": []}
new_dict = dict(filter(lambda x: x is not None and x != "" and x != [], original_dict.items()))
print(new_dict)
# 输出:{"a": 1}
```
阅读全文