I have a task to get keys with maximum values. What I have now works except for when the max appears more than once. So, for example {a:2,b:1,c:2} right now this returns just a but I need it to return both a and c. I know there are question like this already but I need it to NOT have any built in functions
Here's the code I already have:
maximum = 0
result = []
max_key = None
for i in scores:
value = scores[i]
if value > maximum:
maximum = scores[i]
max_key = i
return max_key
CodePudding user response:
Hint: You need to loop over the scores twice: once to get the max value, and a second time to get all of the keys with that value.
CodePudding user response:
Here's a way:
scores = {'a':2,'b':1,'c':2}
high = None
for score in scores.values():
if high is None or score > high:
high = score
keys = [k for k, v in scores.items() if v == high]
print(keys)
First loop finds the maximum (without using the built-in max()
function). Then, a list comprehension collects all keys in the input scores
with value matching the maximum.
CodePudding user response:
Iterates through dict, replacing results if new max found, and adding index to results if same max found.
def fancy_max(scores):
maximum = 0
for i in scores:
value = scores[i]
if value > maximum:
maximum = value
result = [i]
elif value == maximum:
result.append(i)
return result
s = {'a':2,'b':1,'q':5, 'c':2, 'd':4, 'j':5}
out = fancy_max(s)
print(out)
Output:
['q', 'j']