在python词典中查找术语

时间:2014-03-02 14:51:18

标签: python dictionary

说我是否有一个口袋妖怪列表:

not_e =     {"Bulbasaur": ["Overgrow", "Tackle", "Leech Seed"],
                  "Charmander": ["Blaze", "Scratchy", "Growl"],
                  "Squirtle": ["Torrent", "Tackle", "Tail Whip"],
                  "Pikachu": ["Static", "Tail Whip", "Thunder Shock"],
                  "Haunter": ["Levitate", "Hypnosis", "Spite"],}

并说如果我想选择一个随机的口袋妖怪,我这样做:

random_pokemon = ["Bulbasaur", "Charmander", "Squirtle", "Pikachu", "Haunter"] 
rand_pokemon = random.choice(random_pokemon) 
print("Your pokemon is: " + rand_pokemon)

我如何搜索该词典中的随机口袋妖怪,并从中获取权力列表?

2 个答案:

答案 0 :(得分:2)

# this randomly selects the character.
character = random.choice(not_e.keys())

# this prints the powers of the randomly selected characters.
print not_e[character]

如果您想要的是随机选择的小精灵字符的强大功能,您可以将两个语句组合在一起,如下所示

print not_e[random.choice(not_e.keys())]

答案 1 :(得分:0)

如果您想以更加用户友好的格式打印权力列表,请使用:

print ' '.join(not_e[character])

这将打印由空格分隔的所有权力。如果您想用新行分隔它们,请使用

print '\n'.join(not_e[character])