Random Python dictionary key, weighted by values

dictionary, python, random

Solution

This would work:

random.choice([k for k in d for x in d[k]])

Problem

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.

Original source

Related problems