[Python] Getting lowest non-zero value from a dictionary

Discussão em 'Python' iniciado por Stack, Abril 15, 2025.

  1. Stack

    Stack Membro Participativo

    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.

    Edit


    Was doing some more testing and the dictionaries received had a chance to be full of zero values or the same positive integer. Which made the solution a bit wonky. Decided to change it up a bit and iterate over the items instead by assigning a start value for both highest and lowest. When iterating through the dictionary I assigned new values to highest and lowest if they were either > or < respectively. Something like the code below. (Tried to comment with some code, but the formatting got messed up, so decided to edit the question a bit instead).

    Highest = -1
    Lowest = 1000000 # Highest Value the dictionary values may have
    for key in dict:
    if dict[key] > Highest and dict[key] != 0:
    Highest = dict[key]
    if dict[key] < Lowest and dict[key] != 0:
    Lowest = dict[key]

    # Then possible to iterate over the dictionary and get the highest and lowest values from the dictionary.
    for key, value in dict.items():
    if value == Highest and Highest != -1:
    Do X
    elif value != 0:
    if value == Lowest and Lowest != 1000000:
    Do Y
    else:
    Do z
    else:
    Do z

    Continue reading...

Compartilhe esta Página