How should we get the key of the highest value in python dictionary without using a inbuilt functions
{1: 1, 2: 1, 3: 1, 4: 3, 5: 2} **Expecting answer to be 4**
This can be easily done by
max_key = max(check, key=lambda k: check[k])
But wanted to try without builtin function(without max, lambda)
Any help is much appreciated
my full code
def array(num):
check={}
for i in range(len(num)):
if num[i] in check:
check[num[i]]+=1
else:check[num[i]]=1
max_key = max(check, key=lambda k: check[k])
array([1,2,3,4,5,4,5,4])
Function below perform simple loop thought dictionary and return biggest value of key without any builtins:
def get_max_val_key(data):
max_value = None
for key in data:
if max_value is None or max_value < data[key]:
max_value = data[key]
max_key = key
return max_key
data = {'a':11, 'b':12}
print(get_max_val_key(data))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With