user10786574
user10786574

Reputation:

How to randomly select one item from every list of a dictionary?

I have a dictionary:

>>> print(dict)
{'gs': ['bags', 'begs', 'bogs'],
 'le': ['Cole', 'Dale', 'Dole'],
 'll': ['Ball', 'Bell', 'Bill']}

For every single key I want to pick only one word (randomly) from its list. The output would be like:

{'gs': begs, 'le': 'Cole', 'll': 'Bill'}

and so on.

I have tried loads of things but none has given me a word for every key of the dictionary. Is there a simple way of doing that?

Upvotes: 5

Views: 609

Answers (2)

Gixuna
Gixuna

Reputation: 86

I think one easy way would be to pick a random number between 0 and the length of each list and then picking the item that corresponds to that index! Just iterate through the dictionary's keys (using list(yourdictionary)), get each list, find its length, choose the random number and finally get the element.

Upvotes: 0

Jean-François Fabre
Jean-François Fabre

Reputation: 140186

just use random.choice on the values of the dictionary, rebuilding a dict comprehension with only 1 name as value

import random
d = {'gs': ['bags', 'begs', 'bogs'],
'le': ['Cole', 'Dale', 'Dole'],
'll': ['Ball', 'Bell', 'Bill']}


result = {k:random.choice(v) for k,v in d.items()}

one output:

{'gs': 'bogs', 'le': 'Dale', 'll': 'Bell'}

Upvotes: 5

Related Questions