-3

I have tried both list sorting and dictionary sorting. I don’t understand the dictionary sorting in this kind of list. The key sorting is sorted by name. How can I sort by the following results? I can extract Out the key and value, but how to turn the key and value into a dictionary

subject_score=[{'Mathematics': '56','Language': '48','English': '45','Chemistry': '12','Biology': '45'}] 
for i in subject_score
   for key, value in i.items():
       print(key,value)
dict1={}
dict2=sorted(dict1.items(),key=lamda dict1: dict1[1], reverse=False)
Kofi
  • 1,224
  • 1
  • 10
  • 21
  • Please [provide your code as text as part of the question](https://meta.stackoverflow.com/questions/285551/why-not-upload-images-of-code-errors-when-asking-a-question) – Grismar Dec 19 '21 at 03:53
  • 2
    Does this answer your question? [How do I sort a dictionary by value?](https://stackoverflow.com/questions/613183/how-do-i-sort-a-dictionary-by-value) – Grismar Dec 19 '21 at 03:54
  • unfortunately no. I keep getting the same error – Kofi Dec 20 '21 at 04:26

1 Answers1

1

I think you are having issues because your numbers are strings instead of ints. Removing the quotes around the numbers should fix everything.

subject_score=[{'Mathematics': 56,'Language': 48,'English': 45,'Chemistry': 12,'Biology': 45}]
dict2 = {key: value for key, value in sorted(subject_score[0].items(), key = lambda item: item[1], reverse = True)}
print(dict2)

returns:

{'Mathematics': 56, 'Language': 48, 'English': 45, 'Biology': 45, 'Chemistry': 12}
laserjeff
  • 26
  • 3
  • I don't think this was OP's question, but +1 since comparing numbers as strings will just compare the first non-itentical digit so it may cause unexpected behavior. It might be helpful to the OP to preserve the data types they're already using, so it might be preferable to change the sorting function to cast the numbers as integers instead of modifying the dictionary. So `key = lambda item: int(item[1])` – Elijah Cox Dec 19 '21 at 06:10