Reputation: 63
I'm trying to make a sorting system with card ranks and their values are obtained from a separate dictionary. In a simple deck of 52 cards, we have 2 to Ace ranks, in this case I want a ranking system where 0 is 10, J is 11, Q is 12, K is 13, A is 14 and 2 is 15 where 2 is the largest valued rank. The thing is, if there is a list where I want to sort rank cards in ASCENDING order according to the numbering system, how do I do so?
For example, here is a list, [3,5,9,7,J,K,2,0]
, I want to sort the list into [3,5,7,9,0,J,K,2]
. I also made a dictionary for the numbering system as {'A': 14, 'K': 13, 'J': 11, 'Q': 12, '0': 10, '2': 15}
.
THANKS
Upvotes: 3
Views: 204
Reputation: 1095
This answer works:
sorted(list_for_sorting, key=dictionary_you_wrote.__getitem__)
This does too:
sorted_list = sorted(unsorted_list, key = lambda k: your_dictionary[k])
The sorted function uses each entry in the first argument (the object you want to sort), to call the second argument. That way the lamda function returns the value for the given item from the dictionary and sorted can use it as the key.
If any list entry is not in your_dictionary.keys(), this will not work. Either complete the dictionary or use
sorted(unsorted_list, key = lambda k: your_dictionary[k] if k in your_dictionary.keys() else k)
Upvotes: 1
Reputation: 325
have you already tried
sorted(list_for_sorting, key=dictionary_you_wrote.__getitem__)
?
Upvotes: 0