I am attempting to loop over a dictionary with a for
loop to display keys and values in order of one of the value elements(the batting order number).
I can print the keys and values in the intended format, but I cannot figure out how to get the lines in the correct batting order.
I need to complete this task with logic in a for loop and without the use of lambda or a function. Here is what I have so far:
print ('Rays starters' + "\n")
rays_starters = {
'DeJesus' : ['DH', 6, 299],
'Loney' : ['1B', 4, 222],
'Rivera' : ['C', 9, 194],
'Forsythe' : ['2B', 5, 304],
'Souza Jr' : ['RF', 2, 229],
'Longoria' : ['3B', 3, 282],
'Cabrera' : ['SS', 7, 214],
'Kiermaier' : ['CF', 1, 240],
'Guyer' : ['LF', 8, 274] }
for player in rays_starters:
print (player + str(rays_starters[player]))
print ('\n' + 'Today\'s lineup' + '\n')
for player in rays_starters:
batting_order = rays_starters.get(player)
print('Batting ' + str(batting_order[1]) + ' : ' + str(batting_order[0]) + ' ' + player + ' ,current avg: ' + str(batting_order[2]))
The output should look like this:
Rays starters
DeJesus ['DH', 6, 299]
Loney ['1B', 4, 222]
Rivera ['C', 9, 194]
Forsythe ['2B', 5, 304]
Souza Jr ['RF', 2, 229]
Longoria ['3B', 3, 282]
Cabrera ['SS', 7, 214]
Kiermaier ['CF', 1, 240]
Guyer ['LF', 8, 274]
Today's lineup
Batting 1 : CF Kiermaier ,current avg: 240
Batting 2 : RF Souza Jr ,current avg: 229
Batting 3 : 3B Longoria ,current avg: 282
Batting 4 : 1B Loney ,current avg: 222
Batting 5 : 2B Forsythe ,current avg: 304
Batting 6 : DH DeJesus ,current avg: 299
Batting 7 : SS Cabrera ,current avg: 214
Batting 8 : LF Guyer ,current avg: 274
Batting 9 : C Rivera ,current avg: 194
My output does in fact look exactly like this with the exception of the batting order being out of order. Please help me get on the right track and remember I am trying to learn here so any helpful criticism is welcome!
Here's an efficient way since we know there are going to be 9 batters.
lineup = [None] * 9
for player, stats in rays_starters.items():
lineup[stats[1]-1] = player, stats
print ('\nToday\'s lineup\n')
for player, batting_order in lineup:
print('Batting ' + str(batting_order[1]) + ' : ' + str(batting_order[0]) + ' ' + player + ' ,current avg: ' + str(batting_order[2]))
All we are doing is initializing an array of 9 elements and using the batting order to map the player and stats as a tuple to the correct array index. Then we loop through the array of player and statistics tuples, and print the desired formatted output. This is O(n).
This concept is basically derived from Radix sort, or, more specifically, a very simple case of Counting sort where all the frequences are 1 and the "key function" is just subtracting 1 from the batting order to get an array index.
As @PadraicCunningham notes in the comments, this can theoretically be used for any number of batters by using the len
function.
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments