I have a dictionary with two values (id and amount):
JavaScript
x
2
1
dict={5: [379], 11: [396], 6: [480], 19: [443]}
2
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:
JavaScript
1
3
1
max=6
2
min=5
3
Advertisement
Answer
You could just calculate it with a for loop:
JavaScript
1
11
11
1
input = {5: 379, 11: 396, 6: 480, 19: 443}
2
3
keys = input.keys()
4
largest_key = keys[0]
5
6
for key in keys:
7
if input[key] > input[largest_key]:
8
largest_key = key
9
10
print(largest_key)
11
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.
JavaScript
1
11
11
1
input = {5: [379], 11: [396], 6: [480], 19: [443]}
2
3
keys = input.keys()
4
largest_key = keys[0]
5
6
for key in keys:
7
if input[key][0] > input[largest_key][0]:
8
largest_key = key
9
10
print(largest_key)
11
To get the min you would use this exact same process but switch the operator to less than.