Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Randomly Keep X Percent of Dictionary

Tags:

python

django

I'm struggling with this one.

I need to randomly keep X percent of a dictionary for some analysis I'm doing.

A user would input a percentage of the data they would like to keep.
Example values: 10, 50, 70, 100

So when a user enters 30, how would I go about keeping 30 of every 100th element randomly?

I tried the below but it's not working because I need a dictionary back. Suggestions?

images = {}
for vote in votes_selected:
    images[int(vote['id_left'])] = 1
    images[int(vote['id_right'])] = 1
selected_images = random.sample(images, int(len(images) * 50/100))
like image 469
Phil Salesses Avatar asked Feb 22 '23 15:02

Phil Salesses


1 Answers

If ordering doesn't matter...

import random
random.sample(votes_selected, int(len(votes_selected) * DATA_PERCENTAGE / 100))

P.S. If votes_selected is actually a dict, then you can do this:

dict(random.sample(votes_selected.iteritems(), int(len(votes_selected) * DATA_PERCENTAGE / 100)))
like image 61
Amber Avatar answered Mar 06 '23 04:03

Amber