Top-k on a list of dict in python
<p>Is there an easy way to perform the max k number of key:values pair in this example </p>

<pre><code>s1 = {'val' : 0}
s2 = {'val': 10}
s3 = {'val': 5}
s4 = {'val' : 4}
s5 = {'val' : 6}
s6 = {'val' : 7}
s7 = {'val' : 3}
shapelets = [s1,s2,s3,s4,s5,s6,s7]
</code></pre>

<p>I want to get the max 5 numbers in the shapelets list, knowing that it contains a key of name "val" and to which a value is assigned.
The solution here resides in parsing through the list of dict elements and get the max n numbers of it ( in this case the max 5 values )</p>

<p>What can be a simple solution, does operator library in python supports such operation ?</p>

<p>You can use <a href="https://docs.python.org/3.0/library/heapq.html" rel="nofollow"><code>heapq</code></a>:</p>

<pre><code>import heapq

s1 = {'val': 0}
s2 = {'val': 10}
s3 = {'val': 5}
s4 = {'val': 4}
s5 = {'val': 6}
s6 = {'val': 7}
s7 = {'val': 3}
shapelets = [s1, s2, s3, s4, s5, s6, s7]

heapq.nlargest(5,[dct['val'] for dct in shapelets])
# [10, 7, 6, 5, 4]
</code></pre>

<p><code>heapq</code> is likely to be faster than <code>sorted</code> for large <code>lists</code> if you only want a few of the largest values. Some discussions of <code>heapq</code> vs. <code>sorted</code> are <a href="http://stackoverflow.com/questions/24666602/python-heapq-vs-sorted-complexity-and-performance">here</a>.</p>

python list dictionary