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>Instead of <code>v</code>, you have to just mention <code>v[0]</code> that is the is the index in value on which you want to sort.</p>

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

<p>Additonal piece of info, you may remove <code>reversed=True</code> param in the call and replace <code>v[0]</code> with <code>-v[0]</code>. Result will be same:</p>

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

python list sorting dictionary ordereddictionary