
- Python 3 Basic Tutorial
- Python 3 - Home
- What is New in Python 3
- Python 3 - Overview
- Python 3 - Environment Setup
- Python 3 - Basic Syntax
- Python 3 - Variable Types
- Python 3 - Basic Operators
- Python 3 - Decision Making
- Python 3 - Loops
- Python 3 - Numbers
- Python 3 - Strings
- Python 3 - Lists
- Python 3 - Tuples
- Python 3 - Dictionary
- Python 3 - Date & Time
- Python 3 - Functions
- Python 3 - Modules
- Python 3 - Files I/O
- Python 3 - Exceptions
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.
- Related Articles
- How to sum values of a Python dictionary?
- How to replace values of a Python dictionary?
- How to print all the values of a dictionary in Python?
- How to replace values in a Python dictionary?
- Python program to find the highest 3 values in a dictionary
- How to update a Python dictionary values?
- How to check if all the values in a numpy array are non-zero?
- How to sort a dictionary in Python by values?
- Python program to find average score of each students from dictionary of scores
- Find the highest 3 values in a dictionary in Python program
- How to get a list of all the values from a Python dictionary?
- Accessing Values of Dictionary in Python
- How to concatenate a Python dictionary to display all the values together?
- Python – Limit the values to keys in a Dictionary List
- How to find the Average Values of all the Array Elements in C#?

Advertisements