I have a (potentially) huge dict in Python 3.10 and want to randomly sample a few values. Alas, random.sample(my_dict, k)
says:
TypeError: Population must be a sequence. For dicts or sets, use sorted(d).
and random.sample(my_dict.keys(), k)
gives
DeprecationWarning: Sampling from a set deprecated
since Python 3.9 and will be removed in a subsequent version.
I don't want to pay the cost of converting my dictionary keys to a list, and I don't need them sorted.
There's an old question in a similar vein, but that's from before stuff got deprecated in Python and the person asking that question didn't mind converting to a list first.
I also tried running random.choice
multiple times to simulate random.sample
. But that's even worse: it just throws an exception when you use it on a dict. (Instead of giving you a reasonable error message.)