从字典中随机抽取键值对的最佳方法是什么?

What is the best way to randomly sample key, value pairs from a dictionary?

假设有人有一本字典,想随机抽取 key/value 对的子集,最好的方法是什么?

以前,我会使用 random.sample,但显然此功能将不再用于集合。是否存在可以产生相同结果的现有功能?

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]}

您可以将 set 转换为 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))