I have a dictionary where each key has a list of variable length, eg:
d = { 'a': [1, 3, 2], 'b': [6], 'c': [0, 0] }
Is there a clean way to get a random dictionary key, weighted by the length of its value? random.choice(d.keys())
will weight the keys equally, but in the case above I want 'a'
to be returned roughly half the time.
To get the key from the value in the dictionary, use list comprehension and items() method.
To get a random value from a dictionary in Python, you can use the random module choice() function, list() function and dictionary values() function. If you want to get a random key from a dictionary, you can use the dictionary keys() function instead.
In python, if we want a dictionary in which one key has multiple values, then we need to associate an object with each key as value. This value object should be capable of having various values inside it. We can either use a tuple or a list as a value in the dictionary to associate multiple values with a key.
values()[0] to pull out the first value of a list inside a dictionary. Bookmark this question.
This would work:
random.choice([k for k in d for x in d[k]])
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With