Python - Filter the negative values from given dictionary

As part of data analysis, we often encounter scenarios where we need to filter out negative values from a dictionary. Python provides several approaches to accomplish this task efficiently. Below are two common methods using different programming constructs.

Using Dictionary Comprehension

Dictionary comprehension provides a clean and readable way to filter negative values. We iterate through each key-value pair and include only those with non-negative values ?

Example

dict_1 = {'x': 10, 'y': 20, 'z': -30, 'p': -0.5, 'q': 50}

print("Given Dictionary:", dict_1)

filtered_dict = {key: value for key, value in dict_1.items() if value >= 0}

print("After filtering negative values:", filtered_dict)

Output

Given Dictionary: {'x': 10, 'y': 20, 'z': -30, 'p': -0.5, 'q': 50}
After filtering negative values: {'x': 10, 'y': 20, 'q': 50}

Using Lambda Function with Filter

The filter() function combined with lambda provides a functional programming approach. This method is particularly useful when you want to apply complex filtering logic ?

Example

data_dict = {'x': -4/2, 'y': 15, 'z': -7.5, 'p': -9, 'q': 17.2}

print("Given Dictionary:", data_dict)

filtered_dict = dict(filter(lambda item: item[1] >= 0.0, data_dict.items()))

print("After filtering negative values:", filtered_dict)

Output

Given Dictionary: {'x': -2.0, 'y': 15, 'z': -7.5, 'p': -9, 'q': 17.2}
After filtering negative values: {'y': 15, 'q': 17.2}

Comparison

Method Readability Performance Best For
Dictionary Comprehension High Faster Simple filtering conditions
Lambda with filter() Medium Slightly slower Complex filtering logic

Conclusion

Dictionary comprehension is generally preferred for filtering negative values due to its readability and performance. Use filter() with lambda when you need more complex filtering conditions or want to apply functional programming principles.

Updated on: 2026-03-15T17:28:34+05:30

600 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements