我有一本字典:
dict = {
"Apple": ["Green", "Healthy", "Sweet"],
"Banana": ["Yellow", "Squishy", "Bland"],
"Steak": ["Red", "Protein", "Savory"]
}
我想从每个键中打印一个随机值,所以我试着先把它们放到一个列表中:
import random
food = [dict.value.random.choice()]
但这并不起作用(毫不奇怪,它看起来过于混乱)
然后我想要print
食物:
print food
然后看看:
green
squishy
savory
或随机选择的任何值。
创建列表是不必要的?我会不断发帖。
只是为了澄清为什么这不重复:我不想从字典中随机抓取一个项目,我想从字典中的每个列表中随机抓取一个项目。
答案 0 :(得分:5)
您可以使用列表推导来循环遍历您的值:
>>> 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']
对于您想要的打印,您可以使用join
函数或循环遍历food
并逐个打印元素:
>>> print '\n'.join(food)
Savory
Green
Squishy
>>> for val in food :
... print val
...
Savory
Green
Squishy
答案 1 :(得分:3)
您还可以使用for循环:
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
结果:
Red Steak
Healthy Apple
Bland Banana
答案 2 :(得分:3)
使用列表推导,如
import random
choices = [random.choice(v) for k, v in your_dict.items()] # iterate over the dict items
print(choices)
输出
['Protein', 'Green', 'Squishy']
答案 3 :(得分:1)
(BTW-将名称'dict'更改为其他内容)
# for python3
from random import randint
data = {
"Apple": ["Green", "Healthy", "Sweet"],
"Banana": ["Yellow", "Squishy", "Bland"],
"Steak": ["Red", "Protein", "Savory"]
}
for key, value in data.items():
print(key + ":" + value[randint(0,2)])
输出(将根据随机int值更改)
sh-4.2# python3 main.py
Apple:Sweet
Steak:Red
Banana:Squishy
修正案01(@ Selcuk的问题)
for key, value in data.items():
length = len(value)
print(key + ":" + value[randint(0,length-1)])
答案 4 :(得分:0)
在彻底浏览文档并使用上面提供的所有非常有用的答案之后,我发现这是最干净和最明显的:
import random
food_char = {
"Apple": ["Green", "Healthy", "Sweet"],
"Banana": ["Yellow", "Squishy", "Bland"],
"Steak": ["Red", "Protein", "Savory"]
}
food=[random.choice(i) for i in food_char.values()]
for item in food:
print item