Skip to content
Advertisement

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

Advertisement

Answer

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.

User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement