1

While searching for an answer to this question I found that many posts were either concerned more with ordering by keys of each dictionary in a list or the dictionaries within the lists had descriptions for each value like:
[{'name': 'john'}, {'name': 'sam'}] possibly making it easier to order each dictionary.

I have a list of dictionaries in the following format:

[{'Emma': 20}, {'Jake': 15}, {'John': 22}]

How can I order this list by each users age using sorted and lambda only (if possible)?

Any help would be much appreciated.

Huxleyer98
  • 13
  • 4
  • `sorted(source, key=lambda x: next(iter(x.values())))` – Olvin Roght Apr 01 '20 at 14:17
  • already answererd [here](https://stackoverflow.com/questions/9001509/how-can-i-sort-a-dictionary-by-key) – Aven Desta Apr 01 '20 at 14:19
  • Does this answer your question? [How can I sort a dictionary by key?](https://stackoverflow.com/questions/9001509/how-can-i-sort-a-dictionary-by-key) – Aven Desta Apr 01 '20 at 14:19
  • 2
    is there is only one user per dictionary why are there many dictionaries in a list and not just a single dictionary? Also if you need a certain order, you probably need to switch to tuples or so – Ma0 Apr 01 '20 at 14:20
  • Perfect @OlvinRoght thanks very much! – Huxleyer98 Apr 01 '20 at 14:30

1 Answers1

3

You can use next() to get first of dict values:

source = [{'Emma': 20}, {'Jake': 15}, {'John': 22}]
sorted_source = sorted(source, key=lambda x: next(iter(x.values())))
Olvin Roght
  • 7,677
  • 2
  • 16
  • 35