-2

The following is my list

List_data = [{'cases_covers': 0.1625}, {'headphone': 0.1988}, {'laptop': 0.2271}, {'mobile': 0.2501}, {'perfume': 0.4981}, {'shoe': 0.1896}, {'sunglass': 0.1693}]

Final answer should be like this:

[{'perfume': 0.4981}, {'mobile': 0.2501}, {'laptop': 0.2271}, {'headphone': 0.1988},{'shoe': 0.1896}, {'sunglass': 0.1693},{'cases_covers': 0.1625}]

i want them to be sorted based on the value of the key in descending order

大陸北方網友
  • 3,696
  • 3
  • 12
  • 37
  • Does this answer your question? [How do I sort a list of dictionaries by a value of the dictionary?](https://stackoverflow.com/questions/72899/how-do-i-sort-a-list-of-dictionaries-by-a-value-of-the-dictionary) – Rakesh Sep 08 '20 at 09:21
  • "i want them to be sorted based on the value of the key in descending order" actually, in your example, `"perfume", "mobile", "laptop"` are the **keys** and `0.4981, 0.2501` are the **values**, according to the standard vocabulary for dictionaries in python. – Stef Sep 08 '20 at 09:23

1 Answers1

2

You can get the list of values of a dictionary d with d.values(). Since your dictionaries have only one entry each, these lists will be singletons. You can use these singleton-lists to sort List_data by supplying a keyword argument to the sort function.

Please note that in your example, "perfume", "mobile", "laptop" are the keys and 0.4981, 0.2501 are the values, according to the standard vocabulary for dictionaries in python.

List_data = [{'cases_covers': 0.1625}, {'headphone': 0.1988}, {'laptop': 0.2271}, {'mobile': 0.2501}, {'perfume': 0.4981}, {'shoe': 0.1896}, {'sunglass': 0.1693}]
List_data.sort(key=lambda d: list(d.values()), reverse=True)
print(List_data)

Output:

[{'perfume': 0.4981}, {'mobile': 0.2501}, {'laptop': 0.2271}, {'headphone': 0.1988}, {'shoe': 0.1896}, {'sunglass': 0.1693}, {'cases_covers': 0.1625}]

Important remark

The previous piece of code was answering your question literally, without knowledge of the context in which you are trying to sort this list of dictionaries.

I am under the impression that your use of lists and dictionaries is not optimal. Of course, without knowledge of the context, I am only guessing. But perhaps using only one dictionary would better suit your needs:

dictionary_data = {'cases_covers': 0.1625, 'headphone': 0.1988, 'laptop': 0.2271, 'mobile': 0.2501, 'perfume': 0.4981, 'shoe': 0.1896, 'sunglass': 0.1693}
list_data = sorted(dictionary_data.items(), key=lambda it: it[1], reverse=True)
print(list_data)

Output:

[('perfume', 0.4981), ('mobile', 0.2501), ('laptop', 0.2271), ('headphone', 0.1988), ('shoe', 0.1896), ('sunglass', 0.1693), ('cases_covers', 0.1625)]
Stef
  • 13,242
  • 2
  • 17
  • 28