Adi_S Adi_S - 2 months ago 6
Python Question

Selecting a random tuple from a dictionary

Say I have this:

d={'a':[(1,2),(3,4)],'b':[(9,2),(5,4)],'c':[(2,2),(7,7)]}


where d is a dictionary in python. I'd like to get random tuples out of this corresponding to a particular key using the
random.choice()
method.

This is what I'm doing and it's not working:

random.choice(d['a'].values())

Answer

d['a'] is already a list, so you don't need to call .values() on it.

import random
d = {
    'a': [(1, 2), (3, 4)],
    'b': [(9, 2), (5, 4)],
    'c': [(2, 2), (7, 7)],
}
print(random.choice(d['a']))