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>Did you test what you already had to see whether it still worked? Because it does. When you sort a group of sequences, they are compared "alphabetically" - if the first items of two sequences are equal, their second items are compared, and so on. This means that, in your example, <code>sorted</code> would compare the first element of the value's <code>list</code>. If they are different, the sort order is exactly what it would be if you were comparing the first element only with <code>v[0]</code>. If they are the same, sorting by <code>v[0]</code> would simply ensure an arbitrary order for those elements. Leaving it as <code>(v,k)</code> ensures that if the first elements of the value <code>list</code> are equal, it sorts based on the rest of the elements. If there are two values with identical <code>list</code>s, it sorts based on the key.</p>

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

python list sorting dictionary ordereddictionary