Getting the max and min from a dictionary without using max() and min()

I have a dictionary with two values (id and amount):

dict={5: [379], 11: [396], 6: [480], 19: [443]}

and I want to find the id with the max and min amount from the dictionary without using the max and min functions.

So desired output is:

max=6
min=5

3 answers

  • answered 2020-10-29 22:51 Nick Tindle

    Dictionary’s in python are iterable, that is, you can go through them item by item.

    In this case you could do something like

    for key in dict_a:
        #do something here to find the min and max
        print(key)
    

  • answered 2020-10-29 22:53 Evan Snapp

    You could just calculate it with a for loop:

    input = {5: 379, 11: 396, 6: 480, 19: 443}
    
    keys = input.keys()
    largest_key = keys[0]
    
    for key in keys:
        if input[key] > input[largest_key]:
            largest_key = key
    
    print(largest_key)
    

    If your values are lists, you need to chose what index to use to compare the list with. In the code below I hardcoded zero. If you want to go through the list and find the max value there, that would just be another nested loop.

    input = {5: [379], 11: [396], 6: [480], 19: [443]}
    
    keys = input.keys()
    largest_key = keys[0]
    
    for key in keys:
        if input[key][0] > input[largest_key][0]:
            largest_key = key
    
    print(largest_key)
    

    To get the min you would use this exact same process but switch the operator to less than.

  • answered 2020-10-30 09:45 Alexander Riedel

    You can sort the values of your dict and access the largest and smallest like this:

    my_dict={5: [379], 11: [396], 6: [480], 19: [443]}
    
    
    sorted_list = sorted([value for key,value in my_dict.items()])
    
    max_val = sorted_list[-1][0]
    min_val = sorted_list[0][0]
    
    max_key = list(my_dict.keys())[list(my_dict.values()).index([max_val])]
    min_key = list(my_dict.keys())[list(my_dict.values()).index([min_val])]
    
    print(min_key, max_key)