0

How do I sort this dictionary by roster number? Heres what I have so far.

Roster1={
    'player 1':[],
    'player 2':[],
    'player 3':[],
    'player 4':[]
    }
for n in range(4):
    jersey=int(input("Enter player %s"%n+"'s jersey number:\n"))
    rating=int(input("Enter player %s"%n+"'s rating number:\n"))
    Roster1[f"player {n+1}"]=(int(jersey),int(rating))

**sorted(Roster1, key = lambda x:x[0])
print(Roster1)**

for n in range(len(Roster1)):
    tempjersey=Roster1[f'player {n+1}'][0]
    temprating=Roster1[f'player {n+1}'][1]
    print(f'Jersey number: {tempjersey}, Rating: {temprating}')
    

I tried using sorted and lambda, should I try using a sorted dict?

  • Note: you initialize the dictionary item values to empty lists but you later replace them with tuples of (jersey, rating), which is a little misleading. – jarmod Apr 03 '23 at 15:55
  • You need to assign the result of `sorted` to a variable, it doesn't modify the object in place. – Barmar Apr 03 '23 at 15:56
  • Curious as to what version of python you are running. Prior to 3.7(?) dictionaries were unsorted. I believe that starting with 3.7, dictionaries preserve the order you insert elements, by default. – UnsanitizedInput Apr 03 '23 at 15:56
  • You can't sort a dictionary in place. Dictionaries retain their original insertion order. – Barmar Apr 03 '23 at 15:56
  • Thank you Barmar! I just tried that but unfortunatly now the output is only the dictionary titles and it for some reason still is not sorting it by the roster number. Thank you for you help I am still just very lost unfortunatly – Grace Mcpadden Apr 03 '23 at 15:58
  • Should I do it with a nested list instead of dictionary? – Grace Mcpadden Apr 03 '23 at 15:59

0 Answers0