{
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 :
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']]