python字典去除空值
时间: 2024-05-11 22:13:02 浏览: 212
Python代码源码-实操案例-框架案例-空值处理方案….zip
在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}
```
阅读全文