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.
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']
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With