def weighted_lottery(weights, _random=random.random):
 total = sum(weights.itervalues())
 if (total <= 0):
  raise ValueError('total weight must be positive')
 r = (_random() * total)
 t = 0
 for (key, weight) in weights.iteritems():
  if (weight < 0):
   raise ValueError(('weight for %r must be non-negative' % key))
  t += weight
  if (t > r):
   return key
 raise ValueError(('weighted_lottery messed up: r=%r, t=%r, total=%r' % (r, t, total)))

def weighted_lottery ( weights , _random = random . random ) : total = sum ( weights . itervalues ( ) ) if ( total <= 0 ) : raise ValueError ( 'total weight must be positive' ) r = ( _random ( ) * total ) t = 0 for ( key , weight ) in weights . iteritems ( ) : if ( weight < 0 ) : raise ValueError ( ( 'weight for %r must be non-negative' % key ) ) t += weight if ( t > r ) : return key raise ValueError ( ( 'weighted_lottery messed up: r=%r, t=%r, total=%r' % ( r , t , total ) ) )
randomly choose a key from a dict where values are weights .