Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sorting a list according to a dictionary (beginner)

I have the following list:

listofanimals = ['Dog', 'Cat', 'Frog', 'Tiger', 'Sheep', 'Lion']

I would like to sort this list according to a dictionary:

score_card = {0: 'Sheep', 1: 'Dog', 2: 'Cat', 3: 'Tiger', 4: 'Frog', 5: 'Lion'}

Where the order of the final list has to be from 0 to 5, i.e.

numberorder = [0, 1, 2, 3, 4, 5]

I would like to create this inside a function. This is what I have:

def sorter():
    listofanimals = ['Dog', 'Cat', 'Frog', 'Tiger', 'Sheep', 'Lion']
    score_card = {0: 'Sheep', 1: 'Dog', 2: 'Cat', 3: 'Tiger', 4: 'Frog', 5: 'Lion'} 
    numbers = [0, 1, 2, 3, 4, 5]
    finallist = []
    for i in listofanimals:
        print(numbers[listofanimals.index(i)])
        q.append(numbers[listofanimals.index(i)])
    print(q)
    q = sorted(q)
    finallist = [score_card[j] for j in q]
    return finallist

I could not figure out how to convert listofanimals into numbers, so then I could sort the numbers and then feed back into the dictionary to get the values but I just cannot get it to work. Any help is appreciated.

like image 279
Martin Avatar asked Mar 27 '26 07:03

Martin


2 Answers

invert your dictionary

data = {'Sheep':0, 'Dog':1,  'Cat':2, 'Tiger': 3, 'Frog':4, 'Lion':5} 

(if you need to you can invert it programatically, see other answers)

now you can simply

my_sorted_list = sorted(my_list,key = data.get)
like image 184
Joran Beasley Avatar answered Mar 29 '26 20:03

Joran Beasley


listofanimals = ['Dog', 'Cat', 'Frog', 'Tiger', 'Sheep', 'Lion']
score_card = {0: 'Sheep', 1: 'Dog', 2: 'Cat', 3: 'Tiger', 4: 'Frog', 5: 'Lion'}
inverted_score_card = {v: k for k, v in score_card.items()}

sorted_list = sorted(listofanimals, key=inverted_score_card.__getitem__)
print(sorted_list)

output:

['Sheep', 'Dog', 'Cat', 'Tiger', 'Frog', 'Lion']
like image 34
Boseong Choi Avatar answered Mar 29 '26 21:03

Boseong Choi