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.
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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With