Home > database >  Getting lowest non-zero value from a dictionary
Getting lowest non-zero value from a dictionary

Time:06-18

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.

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.

CodePudding user response:

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)

Note: If you just want the values themselves, and don't care about the keys, this is even easier:

nonzero_values = [v for v in Dict.values() if v > 0]
Highest = max(nonzero_values)
Lowest = min(nonzero_values)

CodePudding user response:

from math import inf

Dict = {"D1": "0", "D2": "2", "D3": "7", "D4": "7", "D5": "4"}
Highest = max(Dict, key=lambda x: Dict[x] or inf)
Lowest = min(Dict, key=lambda x: Dict[x] or inf)
  • Related