Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: How do I randomly select a value from a dictionary key?

I have a dictionary:

dict = {
    "Apple": ["Green", "Healthy", "Sweet"],
    "Banana": ["Yellow", "Squishy", "Bland"],
    "Steak": ["Red", "Protein", "Savory"]
}

and I want to print one random value from each key, so I tried to get them into a list first:

import random

food = [dict.value.random.choice()]

but this doesn't work (no surprise, it looks excessive and confusing)

and I want to then print food:

print food

and just see:

green
squishy
savory

or whatever value was randomly selected.

is creating the list unnecessary? I'll keep posting attempts.

Just to clarify why this is not a duplicate: I don't want to randomly grab an item from a dictionary, I want to randomly grab an item from a each list inside a dictionary.

like image 375
Charles Watson Avatar asked Mar 22 '15 16:03

Charles Watson


2 Answers

You can use a list comprehension to loop over your values :

>>> my_dict = {
...     "Apple": ["Green", "Healthy", "Sweet"],
...     "Banana": ["Yellow", "Squishy", "Bland"],
...     "Steak": ["Red", "Protein", "Savory"]
... }
>>> import random
>>> food=[random.choice(i) for i in my_dict.values()]
>>> food
['Savory', 'Green', 'Squishy']

And for print like what you want you can use join function or loop over food and print the elements one by one :

>>> print '\n'.join(food)
Savory
Green
Squishy
>>> for val in food :
...      print val
... 
Savory
Green
Squishy
like image 91
Mazdak Avatar answered Oct 13 '22 00:10

Mazdak


You can also use a for loop:

import random

dict = {
    "Apple": ["Green", "Healthy", "Sweet"],
    "Banana": ["Yellow", "Squishy", "Bland"],
    "Steak": ["Red", "Protein", "Savory"]
}

for key, value in dict.items():
    print random.choice(value), key

result:

Red Steak
Healthy Apple
Bland Banana
like image 37
Selcuk Avatar answered Oct 13 '22 01:10

Selcuk