-3

I have a list of dictionaries and want each dictionary to be sorted by value

list=[{ 1:0.2, 3:0.1, 5:0.8},{ 6:0.8, 9:0.6, 10:0.7}]

when sorted by value it should become:

[{ 3:0.1, 1:0.2, 5:0.8},{ 9:0.6, 10:0.7, 6:0.8}]

zead seam
  • 31
  • 5
  • 1
    Hi there i think you can find your answer here: https://stackoverflow.com/questions/613183/how-do-i-sort-a-dictionary-by-value after that i just would sort the array by the first element in each dict – Patrick Nov 25 '21 at 11:47
  • 1
    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) – bad_coder Nov 25 '21 at 11:55

1 Answers1

1

Starting from python 3.7 dictionaries are insertion ordered, so you could do it in the following way:

lst = [dict(sorted(d.items(), key=lambda x: x[1])) for d in lst]
Riccardo Bucco
  • 13,980
  • 4
  • 22
  • 50