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>Here's a working 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]

print(sorted(shapelets, key=lambda x: x['val'])[-5:])
</code></pre>

python list dictionary