0

I'm a total python newbie but still search for an elegant way to solve the following task. I already searched through the forum, but I only found very particular solutions for other list problems.

I'm trying to analyze, sort and rearrange an JSON array in python. But I haven't found a working solution so far to sort the list from the lowest to the highest value entries.

this is my example list:

 [{'path': 'file_abc.wav', 'val': [0.49]}, 
  {'path': 'file_dfg.wav', 'val': [0.0]}, 
  {'path': 'file_ejh.wav', 'val': [1.0]}]

I'd like to rearrange the input list the according to its value beginning from the lowest up to the highest:

[{'path_old': 'file_dfg.wav', 'val': [0.0]}, 
 {'path_old': 'file_abc.wav', 'val': [0.49]}, 
 {'path_old': 'file_ejh.wav', 'val': [1.0]}]

I would be very pleased if anybody could give me a hint how to solve this in a good way!

ChrisLos
  • 13
  • 2
  • Possible duplicate of [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) – Maurice Meyer Jan 30 '19 at 11:30

3 Answers3

3

Try this:

sorted(your_list, key=lambda x:x['val'][0])

sorted accepts an argument(key) and if you set it, it will sort that iterable based on that.

Mehrdad Pedramfar
  • 10,941
  • 4
  • 38
  • 59
0
lst = [
  {'path': 'file_abc.wav', 'val': [0.49]}, 
  {'path': 'file_dfg.wav', 'val': [0.0]}, 
  {'path': 'file_ejh.wav', 'val': [1.0]}
]
print(sorted(lst, key=lambda d: d['val'][0]))

This prints:

[
  {'path': 'file_dfg.wav', 'val': [0.0]}, 
  {'path': 'file_abc.wav', 'val': [0.49]}, 
  {'path': 'file_ejh.wav', 'val': [1.0]}
]
sam46
  • 1,273
  • 9
  • 12
0

If you dont to create a new list then you can also use lst.sort(key = lambda function)

aa =  [{'path': 'file_abc.wav', 'val': [0.49]}, 
  {'path': 'file_dfg.wav', 'val': [0.0]}, 
  {'path': 'file_ejh.wav', 'val': [1.0]}]


aa.sort(key = lambda x:x['val'])
print (aa)

#OUTPUT:
#[{'path': 'file_dfg.wav', 'val': [0.0]}, {'path': 'file_abc.wav', 'val': [0.49]}, {'path': 'file_ejh.wav', 'val': [1.0]}]
Akash Swain
  • 520
  • 3
  • 13