How to best diplay a random string, with some strings weighted heavier than others

Question:

I am trying to display a random string but would like some strings to occur more often than others. My current strategy is with nested dictionaries for ease of updating and the ‘choices’ function.

msg_list = {

    'msg_1': {
        'msg': 'Hi',
        'weight': 40,
         },

    'msg_2': {
        'msg': 'hello',
        'weight': 50,
         },

    'msg_3': {
        'msg': "What's up",
        'weight': 10,
        },
    }

message = choices(msg_list['msg'], msg_list['weight'])
string = message['msg']

This obviously doesn’t work, and I imagine I could build the lists with a loop, but I am curious if there is a faster way of doing this. Thanks!

Asked By: rtd730

||

Answers:

You’re almost there.
You just need to create lists for the 2 parameters of random.choices.

msg_list = {

    'msg_1': {
        'msg': 'Hi',
        'weight': 40,
        },

    'msg_2': {
        'msg': 'hello',
        'weight': 50,
        },

    'msg_3': {
        'msg': "What's up",
        'weight': 10,
        },
    }

weights = [msg_list[key]['weight'] for key in msg_list.keys()]
messages = [msg_list[key]['msg'] for key in msg_list.keys()]


message = choices(messages, weights)
string = message[0]
Answered By: Peter Pesch
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.