python - 如何从python中的字典中随机选择一定比例的键值对?
问题描述
我已经有一本字典len(sample)=5
sample={'a':[1,2],'b':[5,2],'c':[88,3],'d':[63,55],'e':[77,9]}
我想制作一个只包含三对的新字典sample
。我怎么做?
解决方案
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)
推荐阅读
- react-native - 删除查询使用 expo-sqlite 从两个表中删除条目
- python - 如何使用 lmxl 或 pykml 从 GE kml 中提取 LineString 元素颜色?
- javascript - 在多个视图中通过 Apps 脚本在表格中追加行
- python - 如何从 Python 读取返回的 Rust dll 指针
- swiftui - 如何使 SceneView 的背景透明?
- typescript - TypeScript:基于泛型构造类型化接口
- visual-studio - 如何在没有 Visual Studio 2019 将其扩展为 <:Phrase> 的情况下添加文本 :Phrase+TAB-Key
- javascript - 将 pause: "hover" 添加到现有 js
- wxpython - StyledTextCtrl 如何更改默认文本选择颜色
- reactjs - 使用不记名令牌的 React API 调用已被 CORS 策略阻止