DISCLAIMER: I know there's a question named
but mine is not a duplicate, clearly. The answers to that question mostly concentrate on computing the sum of the values a random subset of a dictionary, because that's what the OP really wanted. Instead, I really need to extract a subset.
I have a very large dictionary, and I want to extract a subsample, on which I then want to iterate. I tried:
import random
dictionary = {'a':1, 'b':2, 'c':3, 'd':4, 'e':5}
keys = random.sample(dictionary, 3)
sample = dictionary[keys]
But it doesn't work:
Traceback (most recent call last):
File "[..]/foobar.py", line 4, in <module>
sample = dictionary[keys]
TypeError: unhashable type: 'list'
This works:
import random
dictionary = {'a':1, 'b':2, 'c':3, 'd':4, 'e':5}
keys = random.sample(dictionary, 3)
sample = {key: dictionary[key] for key in keys}
It seems a bit word-ish: I hoped there would be a vectorized way to build the new dictionary. However, is this the right/most Pythonic way to do it? Also, if I want to iterate on this sample, should I do like this:
for key, value in sample.iteritems():
print(key, value)
My question is not a duplicate of
how to randomly choose multiple keys and its value in a dictionary python
either, because the answer to that question doesn't full address my question. It's even worse than my attempt: instead than creating a sample dictionary, it samples the keys and then retrieves the values separately. It's obviously not very pythonic, and I explicitly asked for a pythonic answer.