-2

I am currently working on a program for my robotics team the prints out a team key(a string) and a value that ranks how good it is. So the current output I have is a dictionary with the team key as the key and the value as the value. However the dictionary is not sorted. I have read that you can change it to a list of tuples which I have tried and worked, but I have just 1 issue. Currently the team key has 'frc' in front of the team number, and I remove it by doing [3:]. However when I do the same for the list of tuples, it doesn't work. So I was wondering if there was a way to sort the dictionary by its values without changing it to a list of tuples?

Dan yu
  • 47
  • 4
  • Can you break the problem down with example? – Duc Filan Apr 11 '18 at 01:06
  • 1
    If you actual have a reference to the string, the slicing with `[3:]` would work too. I'm guessing you aren't unpacking the `tuple`s as you go, so you're trying to slice the wrong thing. – ShadowRanger Apr 11 '18 at 01:08
  • Did you reject OrderedDict? (https://docs.python.org/3/library/collections.html#ordereddict-examples-and-recipes) – jarmod Apr 11 '18 at 01:09

2 Answers2

2

You could add items to an ordered dict after sorting: https://docs.python.org/2/library/collections.html#collections.OrderedDict

But if you wanted to use a tuple, changing a value in one won't work as they're immutable. However, you could slice before creating it.

(An extension of the top answer here: Python 3 sort a dict by its values)

s = [(k[3:], d[k]) for k in sorted(d, key=d.get, reverse=True)]

0
mydict = {'frc1':40,'frc2':2,'frc3':1,'frc4':3}

for key, value in sorted(mydict.iteritems(), key=lambda (k,v): (k[3:], v)):
    print "%s: %s" % (key, value)

Output:

frc1: 40  
frc2: 2  
frc3: 1  
frc4: 3 

This should work, if I undestand your problem correctly :)

lambda functions are quite magical

Steven Black
  • 1,988
  • 1
  • 15
  • 25