vendredi 2 novembre 2018

Get a random subset of a dictionary [duplicate]

This question already has an answer here:

DISCLAIMER: I know there's a question named

Get a random sample of a dict

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. 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)




Aucun commentaire:

Enregistrer un commentaire