
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Filter Negative Values From Given Dictionary in Python
As part of data analysis, we will come across scenarios to remove the negative values form a dictionary. For this we have to loop through each of the elements in the dictionary and use a condition to check the value. Below two approaches can be implemented to achieve this.
Using for loop
W simply loop through the elements of the list using a for loop. In every iteration we use the items function to compare the value of the element with the 0 for checking negative value.
Example
dict_1 = {'x':10, 'y':20, 'z':-30, 'p':-0.5, 'q':50} print ("Given Dictionary :", str(dict_1)) final_res_1 = dict((i, j) for i, j in dict_1.items() if j >= 0) print("After filtering the negative values from dictionary : ", str(final_res_1))
Output
Running the above code gives us the following result:
Given Dictionary : {'x': 10, 'y': 20, 'z': -30, 'p': -0.5, 'q': 50} After filtering the negative values from dictionary : {'x': 10, 'y': 20, 'q': 50}
Using lambda function
We use a lambda function for a shorter and clearer syntax. In this case we implement the same logic as above but use a lambda function instead.
Example
dictA = {'x':-4/2, 'y':15, 'z':-7.5, 'p':-9, 'q':17.2} print ("\nGiven Dictionary :", dictA) final_res = dict(filter(lambda k: k[1] >= 0.0, dictA.items())) print("After filtering the negative values from dictionary : ", str(final_res))
Output
Running the above code gives us the following result:
Given Dictionary : {'x': -2.0, 'y': 15, 'z': -7.5, 'p': -9, 'q': 17.2} After filtering the negative values from dictionary : {'y': 15, 'q': 17.2}
Advertisements