简体   繁体   English

如何从 python 中的字典打印一行 3

[英]How to print a single line from a dictonary in python 3

Beginner here writing a code in IDLE that goes like this.初学者在 IDLE 中编写这样的代码。 I need it to prompt the user to enter a stall number.我需要它来提示用户输入摊位号。 Then tell the user the animal, food type, and feeding time associated with that stall.然后告诉用户与该摊位相关的动物、食物类型和喂食时间。 This is the code I have to accompany this.这是我必须附带的代码。

stalls = {101: 'Zebras',
          102: 'Elephants',
          103: 'Geese',
          104: 'Sheep',
          105: 'Turtle',
          106: 'Cheetah',
          107: 'Giraffe',
          108: 'Capybara',
          109: 'Monkeys',
          110: 'Turkey',
          111: 'Guinea Pigs',
          112: 'Possum',
          113: 'Goats',
          114: 'Lions',
          115: 'Tigers'}

food_types = {101: 'Grass',
              102: 'Vegetables',
              103: 'Worms',
              104: 'Grass',
              105: 'Vegetables',
              106: 'Meat',
              107: 'Vegetables',
              108: 'Vegetables',
              109: 'Fruit',
              110: 'Worms',
              111: 'Fruit',
              112: 'Worms',
              113: 'Grass',
              114: 'Meat',
              115: 'Meat'}

feeding_times = {101: '0730',
                 102: '0900',
                 103: '0845',
                 104: '0930',
                 105: '0745',
                 106: '0805',
                 107: '0800',
                 108: '0808',
                 109: '0953',
                 110: '0738',
                 111: '0747',
                 112: '2000',
                 113: '1005',
                 114: '0923',
                 115: '0843'}

stall_choice =  input (int("Which animal are you looking for? Please enter stall number. "))

If I input 111, I am expecting an output of something like "stall number 111 eats Fruit at 0747" How do I print a dictionary by specific line?如果我输入 111,我期待 output 类似“111 号摊位在 0747 吃水果”之类的内容 如何按特定行打印字典? I am aware there are other ways of creating a program like this but I am getting some practice with the use of dictionaries.我知道还有其他方法可以创建这样的程序,但我正在练习使用字典。 Thank you!谢谢!

Use dictionary[key] .使用dictionary[key] Also, it's int(input()) , not input(int()) .此外,它是int(input()) ,而不是input(int()) Take a look below:看看下面:

# Define dictionaries
stall_choice = int(input('...'))
print(f"stall number {stall_choice} (which is {stalls[stall_choice]}), eats {food_types[stall_choice]} at time {feeding_times[stall_choice]}")

Here, I've used f-strings, but you could also use .format() .在这里,我使用了 f 字符串,但您也可以使用.format()

Output: Output:

stall number 111 (which is Guinea Pigs), eats Fruit at time 0747

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM