0
{'Adam': {('Cleaning',4), ('Tutoring',2), ('Baking',1)},
'Betty': {('Gardening',2), ('Tutoring',1), ('Cleaning',3)},
'Charles': {('Plumbing',2), ('Cleaning',5)},
'Diane': {('Laundry',2), ('Cleaning',4), ('Gardening',3)}}

def who(db : {str:{(str,int)}}, job: str, min_skill : int) -> [(str,int)]:
    result = []
    if type(min_skill) != int:
        raise AssertionError
    if min_skill < 0 or min_skill > 5:
        raise AssertionError
    for key,value in db.items():
        for item in value:
            if item[0] == job and item[1] >= min_skill:
                result.append((key,item[1]))
    return sorted(result,key = lambda x: x[1],reverse = True )

the who function, which takes a database, a job (str), minimum skill level (int) as arguments; it returns a list of 2-tuples: persons and their skill level, sorted by decreasing skill level. if two people have the same skill level, they should appear alphabetically.

my function is able to sort the list with minimum skill level (int) , but is not able to sort the list alphabetically.

I got the following error:

*Error: who(db,'Cleaning' ,4) -> [('Charles', 5), ('Diane', 4), ('Adam', 4)] but should -> [('Charles', 5), ('Adam', 4), ('Diane', 4)]

can someone help me to fix my code in order to sort both by the minimum skill level (int) and alphabetically.

  • Possible duplicate of http://stackoverflow.com/questions/4233476/sort-a-list-by-multiple-attributes – jackarms Jan 16 '17 at 01:01

2 Answers2

0

Pass a tuple to sorted function as key, negate the second element(skill level) to sort it in descending order, if the skill level ties, it is then sorted by job in ascending order:

sorted(result,key = lambda x: (-x[1], x[0]))

who(db, "Cleaning", 4)
# [('Charles', 5), ('Adam', 4), ('Diane', 4)]
Psidom
  • 209,562
  • 33
  • 339
  • 356
0

You can sort on two attributes by giving the key argument a function that returns a tuple. Try this:

return sorted(result, key = lambda x: (-x[1], x[0]))

Here you make x[1] negative inside the tuple to sort by skill level in decreasing order, then ascending order for the names. This eliminates the need for the reverse=True.

jackarms
  • 1,343
  • 7
  • 14