首页 > 解决方案 > 如何从python中的字典中随机选择一定比例的键值对?

问题描述

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

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

我想制作一个只包含三对的新字典sample。我怎么做?

标签: pythondictionary

解决方案


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)

推荐阅读