在Python中,可以使用不同的方法来过滤字典中的项。以下是几种常见的方法:
1. 使用`filter`函数和`lambda`表达式:
my_dict = {'a': 1, 'b': None, 'c': 3, 'd': None}
filtered_dict = dict(filter(lambda item: item is not None, my_dict.items()))
print(filtered_dict) 输出:{'a': 1, 'c': 3}
2. 使用字典推导式:
d = {'a': '0.0000', 'b': '1.2', 'c': '3.4', 'd': '0.0'}
d_tmp = {key: float(value) for key, value in d.items() if float(value) > 0}
print(d_tmp) 输出:{'b': 1.2, 'c': 3.4}
3. 使用`filter`函数和自定义函数:
def is_not_null(item):
return item is not None
my_dict = {'a': 1, 'b': None, 'c': 3, 'd': None}
filtered_dict = dict(filter(is_not_null, my_dict.items()))
print(filtered_dict) 输出:{'a': 1, 'c': 3}
以上示例展示了如何使用`filter`函数和不同的参数来过滤字典中的项。您可以根据需要选择合适的方法