Get a random sample of a dict

旧城冷巷雨未停 提交于 2019-12-05 22:11:45

Given your example of:

dy = {'a':1, 'b':2, 'c':3, 'd':4, 'e':5}

Then the sum of all the values is more simply put as:

s = sum(dy.values())

Then if it's not memory prohibitive, you can sample using:

import random

values = list(dy.values())
s = sum(random.sample(values, 2))

Or, since random.sample can take a set-like object, then:

from operator import itemgetter
import random

s = sum(itemgetter(*random.sample(dy.keys(), 2))(dy))

Or just use:

s = sum(dy[k] for k in random.sample(dy.keys(), 2))

An alternative is to use a heapq, eg:

import heapq
import random

s = sum(heapq.nlargest(2, dy.values(), key=lambda L: random.random()))

Replace the range(10) with some randome sample from numphy

{v:rows[v] for v in [list(rows.keys())[k] for k in range(10)]}

import random
origin_dict =  {'a':1, 'b':2, 'c':3, 'd':4, 'e':5}
sample_rate = 0.3
random_keys = random.sample(list(origin_dict.keys()), int(sample_rate * len(origin_dict)))
random_values = [origin_dict[k] for k in random_keys]

sample_dict = dict(zip(random_keys, random_values))

output:

{'d': 4, 'c': 3}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!