Annapoornima Koppad Annapoornima Koppad - 3 months ago 8
Python Question

Sorting based on individual columns of lists in a dictionary

I have a dictionary of lists in the following format.

b =
{'a': [1, 1, 1],
'c': [1, 0, 0],
'b': [1, 0, 1],
'e': [0, 0, 1],
'd': [0, 0, 0],
'g': [0, 1, 1],
'f': [0, 1, 0],
'h': [1, 1, 0]
}


What I am looking to do is to sort the lists and display the dictionary based on the columns of the lists. The first column should be sorted, next the second column should be sorted with the third column in the last.

I want my list like this.

b =
{'d': [0, 0, 0],
'e': [0, 0, 1],
'f': [0, 1, 0],
'g': [0, 1, 1],
'c': [1, 0, 0],
'b': [1, 0, 1],
'h': [1, 1, 0],
'a': [1, 1, 1]
}


I can do the sort of the first value of the list like this.

sorted(b.items(), key=lambda e:e[1][0])


and similarly do the second and the third. However, if I sort the first column, the second and third would not be sorted.

So, I did this.

sorted(b.items(), key=lambda e:e[1])


which gives me the right answer. But I am not sure how this is working.

Second, if I do,

sorted(b.values(), reverse=True, key=lambda e:e[0])


Here, it sorts only the first column of the values while the rest two columns are not sorted.

I have my answer, but I am looking for explanations of this is working for some cases and does not work for others.

Thanks in advance.

Answer
sorted(b.items(), key=lambda e:e[1])

works because the lambda is returning the whole lists, e.g. [1, 1, 1], [1, 0, 0]. Python's default rule for sorting lists is exactly what you need, it will sort lists by the first 'column' or entry in the list, if two lists have the same first item, then they will be sorted by the second item, and so on.