Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Return key with highest value

I have the following graph:

graph = {0 : {5:6, 4:8},
1 : {4:11},
2 : {3: 9, 0:12},
3 : {},
4 : {5:3},
5 : {2: 7, 3:4}}

I am trying to return the key that has the highest value in this graph. The expected output in this case would be 2 as key 2 has the highest value of 12.

Any help on how I can achieve this would be greatly appreciated.

like image 840
user8892141 Avatar asked May 01 '26 16:05

user8892141


1 Answers

Find the key whose maximum value is maximal:

max((k for k in graph), key=lambda k: max(graph[k].values(), default=float("-inf")))

The empty elements are disqualified by the ridiculous maximum. Alternately, you can just pre-filter such keys:

max((k for k in graph if graph[k]), key=lambda k: max(graph[k].values()))
like image 50
Amadan Avatar answered May 03 '26 06:05

Amadan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!