Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Random Python dictionary key, weighted by values

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.

like image 323
hoju Avatar asked Jun 29 '09 00:06

hoju


People also ask

Can you get the key of a dictionary by value Python?

To get the key from the value in the dictionary, use list comprehension and items() method.

How do I randomly select a key from a dictionary in Python?

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.

How do you create a dictionary with multiple values per key?

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.

What does .values 0 do in Python?

values()[0] to pull out the first value of a list inside a dictionary. Bookmark this question.


1 Answers

This would work:

random.choice([k for k in d for x in d[k]]) 
like image 156
sth Avatar answered Sep 21 '22 11:09

sth