- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
How to find the average of non-zero values in a Python dictionary?
You can do this by iterating over the dictionary and filtering out zero values first. Then take the sum of the filtered values. Finally, divide by the number of these filtered values.
example
my_dict = {"foo": 100, "bar": 0, "baz": 200} filtered_vals = [v for _, v in my_dict.items() if v != 0] average = sum(filtered_vals) / len(filtered_vals) print(average)
Output
This will give the output −
150.0
You can also use reduce but for a simple task such as this, it is an overkill. And it is also much less readable than using a list comprehension.
Advertisements