0

So I'm trying to help a friend out with a solution where people donate to a cause and randomly get selected. The problem is, the more you donate, the greater the chance you have of being selected.

Say I have a dictionary of people:

people = {
    "Mike":0,
    "Mark":4,
    "Zach":2,
    "Bryan":2,
    "Eddie":1
    "Erin":0,
}

Is there a way that a person can be randomly picked from this dictonary, but based on their value, give them a greater chance of winning?

alani
  • 12,573
  • 2
  • 13
  • 23
DFC302
  • 17
  • 1
  • 6

2 Answers2

2

random module has a choices method that takes weights (it returns a list of k=1 by default, so take the first item):

import random

print(random.choices(list(people.keys()), weights=people.values())[0])

(in case you wonder, as I did, if keys() and values() are in matching order, they are. See Python dictionary: are keys() and values() always the same order?)

See in action here: https://repl.it/repls/AmbitiousVioletMacrolanguage

alani
  • 12,573
  • 2
  • 13
  • 23
njzk2
  • 38,969
  • 7
  • 69
  • 107
0
import random
def flatlist(l): return [item for sublist in l for item in sublist]

biglist = flatlist([[d]*people[d] for d in people])
print('weighted people:', biglist)

winner = random.choice(biglist)
print('winner:', winner)
Colin
  • 3,670
  • 1
  • 25
  • 36
  • Thankyou for this by the way. The comment above was more simple and worked as well. But you also taught me a few things in your comment. So thankyou for that – DFC302 Sep 23 '19 at 02:31