Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Sort array desc and asc pyhton

{
0: ['70', '70', '70', 'A12345678', 'JONE', 'BIT', 70, 'C'],
1: ['80', '80', '80', 'A12334567', 'ERIC', 'DIT', 80, 'CP'],
2: ['55', '60', '70', 'A12345679', 'HARRY', 'BIT', 63, 'P'],
3: ['45', '45', '45', 'A11223344', 'NEW', 'BIT', 45, 'F']
}

I have an array like this in python I need to sort it on bases of index 6 70,80,63,45 values in array. I try to print it but I am unable to sort this type of array .

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

As I said above, I pull the values into a list of its own, then sort the list.

data = {
0: ['70', '70', '70', 'A12345678', 'JONE', 'BIT', 70, 'C'],
1: ['80', '80', '80', 'A12334567', 'ERIC', 'DIT', 80, 'CP'],
2: ['55', '60', '70', 'A12345679', 'HARRY', 'BIT', 63, 'P'],
3: ['45', '45', '45', 'A11223344', 'NEW', 'BIT', 45, 'F']
}

from pprint import pprint
items = list(data.values())
print("Unsorted")
pprint(items)
items.sort( key=lambda l : l[6] )
print("Sorted")
pprint(items)

Output:

Unsorted
[['70', '70', '70', 'A12345678', 'JONE', 'BIT', 70, 'C'],
 ['80', '80', '80', 'A12334567', 'ERIC', 'DIT', 80, 'CP'],
 ['55', '60', '70', 'A12345679', 'HARRY', 'BIT', 63, 'P'],
 ['45', '45', '45', 'A11223344', 'NEW', 'BIT', 45, 'F']]
Sorted
[['45', '45', '45', 'A11223344', 'NEW', 'BIT', 45, 'F'],
 ['55', '60', '70', 'A12345679', 'HARRY', 'BIT', 63, 'P'],
 ['70', '70', '70', 'A12345678', 'JONE', 'BIT', 70, 'C'],
 ['80', '80', '80', 'A12334567', 'ERIC', 'DIT', 80, 'CP']]
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading