Get a random sample of a dict
<p>I'm working with a big dictionary and for some reason I also need to work on small random samples from that dictionary. How can I get this small sample (for example of length 2)? </p>

<p>Here is a toy-model:</p>

<pre><code>dy={'a':1, 'b':2, 'c':3, 'd':4, 'e':5}
</code></pre>

<p>I need to perform some task on dy which involves all the entries. Let us say, to simplify, I need to sum together all the values:</p>

<pre><code>s=0
for key in dy.key:
    s=s+dy[key]
</code></pre>

<p>Now, I also need to perform the same task on a random sample of dy; for that I need a random sample of the keys of dy. The simple solution I can imagine is</p>

<pre><code>sam=list(dy.keys())[:1]
</code></pre>

<p>In that way I have a list of two keys of the dictionary which are somehow random. So, going back to may task, the only change I need in the code is:</p>

<pre><code>s=0
for key in sam:
    s=s+dy[key]
</code></pre>

<p>The point is I do not fully understand how dy.keys is constructed and then I can't foresee any future issue</p>

<p>Given your example of:</p>

<pre><code>dy = {'a':1, 'b':2, 'c':3, 'd':4, 'e':5}
</code></pre>

<p>Then the sum of all the values is more simply put as:</p>

<pre><code>s = sum(dy.values())
</code></pre>

<p>Then if it's not memory prohibitive, you can sample using:</p>

<pre><code>import random

values = list(dy.values())
s = sum(random.sample(values, 2))
</code></pre>

<p>Or, since <code>random.sample</code> can take a <code>set</code>-like object, then:</p>

<pre><code>from operator import itemgetter
import random

s = sum(itemgetter(*random.sample(dy.keys(), 2))(dy))
</code></pre>

<p>Or just use:</p>

<pre><code>s = sum(dy[k] for k in random.sample(dy.keys(), 2))
</code></pre>

<p>An alternative is to use a <code>heapq</code>, eg:</p>

<pre><code>import heapq
import random

s = sum(heapq.nlargest(2, dy.values(), key=lambda L: random.random()))
</code></pre>

python dictionary random python-3.4