[英]Print the list of dictionary variable names
My assignment is: 我的任务是:
Make several dictionaries, where the name of each dictionary is the name of a pet. 制作几个词典,其中每个词典的名称是宠物的名称。 In each dictionary, include the kind of animal and the owner's name.
在每个字典中,包括动物的种类和所有者的名字。 Store these dictionaries in a list called pets.
将这些词典存储在名为pets的列表中。 Next, loop through your list and as you do print everything you know about each pet.
接下来,循环浏览您的列表,并打印您知道的每个宠物的所有内容。
What I have so far: 到目前为止我所拥有的:
rover = {'type': 'dog', 'owner': 'joe'}
blackie = {'type': 'cat', 'owner': 'gail'}
polly = {'type': 'bird', 'owner': 'paul'}
seth = {'type': 'snake', 'owner': 'stan'}
pets = [rover, blackie, polly, seth]
for pet in pets:
print("\nPet Name:", "\nType:", pet['type'].title(), "\nPet Owner:", pet['owner'].title())
Output so far: 目前为止的输出:
Pet Name: Type: Dog Pet Owner: Joe 宠物名称:类型:狗宠物主人:乔
Pet Name: Type: Cat Pet Owner: Gail 宠物名称:类型:猫宠物主人:盖尔
Pet Name: Type: Bird Pet Owner: Paul 宠物名称:类型:鸟宠物主人:保罗
Pet Name: Type: Snake Pet Owner: Stan 宠物名称:类型:蛇宠物主人:斯坦
My Question: 我的问题:
What do I need to add to my code to have the output include the Pet Name? 我需要添加到我的代码中以使输出包含宠物名称?
Desired Output: 期望的输出:
Pet Name: Rover Type: Dog Pet Owner: Joe 宠物名称:流浪者类型:狗宠物主人:乔
Pet Name: Blackie Type: Cat Pet Owner: Gail 宠物名称:Blackie类型:猫宠物主人:盖尔
Pet Name: Polly Type: Bird Pet Owner: Paul 宠物名称:波莉类型:鸟宠物主人:保罗
Pet Name: Seth Type: Snake Pet Owner: Stan 宠物名称:赛斯类型:蛇宠物主人:斯坦
我会将名字存储在字典中。
rover = {'name' : 'rover', 'type': 'dog', 'owner': 'joe'}
You can use an if statement: 您可以使用if语句:
for pet in pets:
for v in pet.values():
if v == 'joe':
print("\nPet Name: Rover", "\nType:", pet['type'].title(), "\nPet Owner:", pet['owner'].title())
if v == 'gail':
print("\nPet Name: Blackie", "\nType:", pet['type'].title(), "\nPet Owner:", pet['owner'].title())
if v == 'paul':
print("\nPet Name: Polly", "\nType:", pet['type'].title(), "\nPet Owner:", pet['owner'].title())
if v == 'stan':
print("\nPet Name: Seth", "\nType:", pet['type'].title(), "\nPet Owner:", pet['owner'].title())
Output: 输出:
'Pet Name: Rover '
'Type: Dog'
'Pet Owner: Joe'
'Pet Name: Blackie'
'Type: Cat'
'Pet Owner: Gail'
'Pet Name: Polly'
'Type: Bird'
'Pet Owner: Paul'
'Pet Name: Seth'
'Type: Snake'
'Pet Owner: Stan'
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.