I have two dictionaries in Python. One is a list of teams and their ranks in a league table, with each team being a key and their ranks being the associated value. The other is data about each team, with the team name being a value of a key:
RankDict = {'Tigers':'1','Lions':'2', 'Pumas':'3', 'Wolves':'4'}
TeamDict = {'TeamRecords':[{'Team': 'Lions', 'Location':'Greenville',
'HomeGround':'Trec Park', 'Coach': 'K. Wilson'},
{'Team':'Pumas', 'Location':'Fairlodge',
'HomeGround':'Fairlodge Fields', 'Coach':'G. Kennedy'}]}
What I want to do is print the details from the TeamDict dictionary based on the rank associated with the team in the RankDict but can’t just do a straight key comparison because the keys aren’t common. Can anyone help me out?
I can’t find anything regarding this type of dictionary comparison in the documentation. Maybe it isn’t even possible?
The following will print the team, the rank and the team details (sorted by rank):
Note that I’m doing a
try/exceptwhen printing the team details becauseTeamDictdoes not contain information about each team.Also note that you should use integers for the ranks in
RankDict, otherwise the above code won’t sort properly when there is a team with, e.g.,'11'as rank (it will sort:'11','2','3','4').