python - Use max function on dictionary with a conditional statement -


i programming football table in there function gets highest amount of points. these points made of no. of wins*3 + no. of draws. if there 2 of same, 1 least draws wins.

currently using dictionary store teams class attributes such name , total points. aware can find highest value using max function in python iterating through keys , values.

what want know how should return 1 least wins if have seperate dictionary format name:losses?

in shorthand, find highest scoring team(s) , if there 2 teams same points, return 1 has least losses.

def getwinner(classlist):     teampoints = {}     losses = {}     item in classlist:         teampoints[item.getname()] = item.getpoints()         losses[item.getname()] = item.getlosses()     return max(teampoints, key=teampoints.get) 

this code gets highest score correctly if there 2 same points different losses.

you can use python's builtin sorted function custom key function comparator. if wnat first result, them, pick first element of list.

def key(element):    return (element["name"] , - element["losses"])  winner = sorted(results, key=key)[0] 

(assuming "results" list dictionaries containing entries each team)


Comments

Popular posts from this blog

php - Wordpress website dashboard page or post editor content is not showing but front end data is showing properly -

How to get the ip address of VM and use it to configure SSH connection dynamically in Ansible -

javascript - Get parameter of GET request -