-2

I have a list of dictionaries with one key and one value only. Keys are always different, value is float number. How do I sort it by value?

example_list = [{'c47-d75 d75-e6b e6b-ff1 ff1-6d6 6d6-e63 e63-80c': 292.1799470129255}, {'805-7fd': 185.56518334219}, {'805-dd3 dd3-088 088-dd3 dd3-80c': 368.5010685728143}, {'805-6b5': 145.897977770909}, {'77e-805 805-7fd': 326.693786870932}, {'323-83d': 131.71963170528})

The result should be sorted by value so the first item should be

{'805-dd3 dd3-088 088-dd3 dd3-80c': 368.5010685728143}

Could you please help?

PetrSevcik
  • 89
  • 1
  • 9
  • 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) – dimcookies Apr 11 '21 at 19:42

3 Answers3

0

To sort the list based on the first value of the dictionary, pass a function to sorted() to extract the first value of the dictionary.

  1. d.values() returns an iterable of the dictionary values
  2. iter() generates an iterator of the dictionary values
  3. Since there is only 1 dictionary value (by assumption), calling next() on the iterator returns the first (and only) value.

To sort by greatest to least value, pass the reverse=True keyword argument to sorted().

def first_value(d):
    return next(iter(d.values()))

example_list = [{'c47-d75 d75-e6b e6b-ff1 ff1-6d6 6d6-e63 e63-80c': 292.1799470129255}, {'805-7fd': 185.56518334219}, {'805-dd3 dd3-088 088-dd3 dd3-80c': 368.5010685728143}, {'805-6b5': 145.897977770909}, {'77e-805 805-7fd': 326.693786870932}, {'323-83d': 131.71963170528}]

sorted_list = sorted(example_list, key=first_value, reverse=True)

print(sorted_list[0])
Anson Miu
  • 1,171
  • 7
  • 6
0

Here's a slightly different approach:

>>> for d in sorted(example_list, key=lambda d: max(d.values()), reverse=True):
...     print(d)
...
{'805-dd3 dd3-088 088-dd3 dd3-80c': 368.5010685728143}
{'77e-805 805-7fd': 326.693786870932}
{'c47-d75 d75-e6b e6b-ff1 ff1-6d6 6d6-e63 e63-80c': 292.1799470129255}
{'805-7fd': 185.56518334219}
{'805-6b5': 145.897977770909}
{'323-83d': 131.71963170528}

This sorts by using the max() function on the values associated with each dictionary. Since there's only one value in each dictionary, it just returns that value.

Honest question, why have a list of dictionaries instead of a single dictionary with key-value pairs?

ddejohn
  • 8,775
  • 3
  • 17
  • 30
0

You can create a new dictionary sorted by values as follows:

{k: v for k, v in sorted(example_dict.items(), key=lambda item: item[1], reverse = True)}

Since you want the values sorted in descending order you should keep the parameter reverse = True, else for ascending order set it to False.

Shivam Roy
  • 1,961
  • 3
  • 10
  • 23