5

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?

1

2 Answers 2

5

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'} 
Sign up to request clarification or add additional context in comments.

8 Comments

Missed out answering this one because I was too busy fixing the question :D ++
the only problem I see in this is that it has to iterate through the entire dictionary. I like the idea of just getting the 'len()' of keys and then randomly picking an index number.
Sorry about that.
@eatmeimadanish not sure what you mean; this is what OP wants. What you describe is not better than this.
choice doesn't iterate. It picks an index in the values list, except that it's transparent.
|
0

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.

Comments