Sorting dictionary of lists based on first value in list
<p>I need to return a dictionary of lists in descending order based on the first number in each list, for example:</p>

<pre><code>{'key1': [2, 3], 'key2': [7, 7], 'key3': [5, 10]}
should return: {'key2': [7, 7], 'key3': [5, 10], 'key1': [2, 3]}
</code></pre>

<p>What I had originally was:</p>

<pre><code>orderedDict = collections.OrderedDict(sorted(dict.iteritems(), key=lambda (k,v):(v,k), reverse=True))
</code></pre>

<p>when the values of the dictionary were simply numbers, but now that I have changed the value of the dictionary to be a list to contain 2 numbers, I'm not sure how to access and sort by the first number..</p>

<p>I'm using Python 2.7. Any help would be greatly appreciated! Thanks!</p>

<p>You are almost there!</p>

<pre><code>collections.OrderedDict(sorted(a.iteritems(), key=lambda (k,v):v[0], reverse=True))
                                                               ^^^^
</code></pre>

<p>When <code>sorted(..)</code> is called with a <code>key=</code> argument, every element of the first parameter is passed to the lambda. In your case, <code>k</code> would be one key (eg: <code>"key1"</code>), and <code>v</code> would be one value (eg: <code>[7,7]</code>). All you need to say from here is: <code>v[0]</code></p>

<pre><code>&gt;&gt;&gt; collections.OrderedDict(sorted(a.iteritems(), key=lambda (k,v):v[0], reverse=True))
OrderedDict([('key2', [7, 7]), ('key3', [5, 10]), ('key1', [2, 3])])
</code></pre>

<hr>

<p><strong>NOTE</strong>: There is a difference between saying: <code>v[0]</code> and <code>(v[0],k)</code>. In the latter case, you are passing a tuple for comparison. It might not do what you'd want. Read up on how tuple comparison works.</p>

python list sorting dictionary ordereddictionary