如何从python的字典中随机选择比例的键值对?

时间:2019-11-21 20:54:08

标签: python dictionary

我已经有一本字典,其中len(sample)=5

sample={'a':[1,2],'b':[5,2],'c':[88,3],'d':[63,55],'e':[77,9]}

我想制作一个新字典,其中仅包含sample中的三对字典。我该怎么办?

1 个答案:

答案 0 :(得分:0)

from random import choice

test = {}
while len(test) < 3:
    t = choice(sample.keys())
    if t not in test.keys():
        test[t] = sample[t]

print(test)