Sorting a list according to a dictionary (beginner)

Viewed 75

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.

4 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)
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']

You can inverted the score_card dictionary to make things easy.

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

sorted(listofanimals,key=lambda x:score_card[x])
# ['Sheep', 'Dog', 'Cat', 'Tiger', 'Frog', 'Lion']

If you don't want to use lambda you can use itemgetter

sorted_dictionary = dict(sorted(score_card.items()))
sorted = []
for key, value in sorted_dictionary.items():
    for item in listofanimals:
        if value == item:
            sorted.insert(key, item)

Output:

['Sheep', 'Dog', 'Cat', 'Tiger', 'Frog', 'Lion']
Related