Sorting based on individual columns of lists in a dictionary
<p>I have a dictionary of lists in the following format.</p>

<pre><code>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]
   }
</code></pre>

<p>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.</p>

<p>I want my list like this.</p>

<pre><code>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]
   }
</code></pre>

<p>I can do the sort of the first value of the list like this.</p>

<pre><code>sorted(b.items(), key=lambda e:e[1][0])
</code></pre>

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

<p>So, I did this.</p>

<pre><code>sorted(b.items(), key=lambda e:e[1])
</code></pre>

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

<p>Second, if I do,</p>

<pre><code>sorted(b.values(), reverse=True, key=lambda e:e[0])
</code></pre>

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

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

<p>Thanks in advance.</p>

<pre><code>sorted(b.items(), key=lambda e:e[1])
</code></pre>

<p>works because the lambda is returning the whole lists, e.g. <code>[1, 1, 1]</code>, <code>[1, 0, 0]</code>. 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.</p>

python sorting dictionary