Suppose one has a dictionary and wants to randomly sample a subset of key/value pairs, what is the best way to do this?
Previously, I would use random.sample
but apparently this functionality will be deprecated for sets. Is there existing functionality that can produce the same result?
In [1]: dct = {'a': [1,2,3], 'b':[4,5,6], 'c':[7,8,9]}
In [2]:{k:v for k,v in random.sample(dct.items(),1)}
<ipython-input-33-f99661a57cc1>:1: DeprecationWarning: Sampling from a set deprecated
since Python 3.9 and will be removed in a subsequent version.
{k:v for k,v in random.sample(dct.items(),1)}
Out[2]: {'a': [1, 2, 3]}
CodePudding user response:
You can just convert the set
into a list
.
import random
dct = {'a': [1,2,3], 'b': [4,5,6], 'c': [7,8,9]}
# Sample 2 keys from the dict
random.sample(list(dct.items()), 2))