Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Getting lowest None 0 value from a dictionary python

I am trying to get the largest and smallest value / values from a dictionary.

Where the lowest value should not be zero, but the closest to it.
If there is a 0 present and the values are K:0 K:3 K:7 K:1 it should return 1 and not 0.

I’ve tried using the min / max functions, but haven’t been able to get them to work properly. Want to get all values even when there are multiple.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Example Dictionary.

Dict = {"D1" : "0", "D2" : "2", "D3" : "7", "D4" : "7", "D5" : "4"}
Highest = max(Dict, key=Dict.get)
Lowest = min(Dict, key=Dict.get)

Only gets me D3 and D1 respectively. Also returns the 0.
Highest works in most cases, but Lowest returns the 0.Should there be a check after lowest has been assigned and iterate over the dictionary again?
Highest and Lowest can be a list or a single Value doesn’t really matter.

My current code looks something like this.

Dict = {"D1" : "0", "D2" : "2", "D3" : "7", "D4" : "7", "D5" : "4"}
Highest = max(Dict, key=Dict.get)
Lowest = min(Dict, key=Dict.get)
for key, value in Dict.items():
    if value == Dict[Highest]:
        Do x
    elif value == Dict[Lowest]:
        Do y
    else:
        Do z

Which mostly works, except for the above mentioned 0 getting returned.

>Solution :

You need to filter first, then min/max the filtered data. Sticking to your design as closely as possible:

nozeroes = {k: v for k, v in Dict.items() if v > 0}  # New dict with only positive values

# Only change to original version is replacing Dict with nozeroes
Highest = max(nozeroes, key=Dict.get)
Lowest = min(nozeroes, key=Dict.get)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading