具有不同名称的字典以及如何打印名称



Pets:创建几个字典,其中每个字典的名称是宠物的名字。在每本词典中,注明动物的种类和主人的名字将这些字典存储在一个名为pets的列表中。接下来,循环浏览列表你也可以把你知道的关于每只宠物的一切都印出来。

你好,我有一个问题。我已经完成了解决方案,但我想打印字典的名称,而不是为每个

写print解决方案:

jumbo = {"kind":"cat",
"owner":"Rahma",
}


snoopy = {"kind":"dog",
"owner":"fahad",
}

shilla = {"kind":"bird",
"owner":"farooq",
}

pets = [jumbo,snoopy,shilla] # created list 
#loop through your list and as you do print everything you know about each pet
for pet in pets :
print ( "jumbo" + " is "+ pet["kind"] + " the owner is " + pet["owner"].title() + "." ) )

问题是我试图在每个循环中打印使用创建的列表宠物的名称

尝试以下两种解决方案:

First - Zip与宠物列表名称:

names = ["jumbo", "snoopy", "shilla"]
# loop through your list and as you do print everything you know about each pet
for name, pet in zip(names, pets):
print(name + " is " + pet["kind"] + " the owner is " + pet["owner"].title() + ".")

第二步:将名字添加到字典中:

jumbo = {"name": "jumbo", "kind": "cat",
"owner": "Rahma",
}
snoopy = {"name": "snoopy", "kind": "dog",
"owner": "fahad",
}
shilla = {"name": "shilla", "kind": "bird",
"owner": "farooq",
}
for pet in pets:
print(pet["name"] + " is " + pet["kind"] + " the owner is " + pet["owner"].title() + ".")

您可以像下面这样使用eval()(参见ref):

jumbo = {"kind":"cat",
"owner":"Rahma",
}
snoopy = {"kind":"dog",
"owner":"fahad",
}
shilla = {"kind":"bird",
"owner":"farooq",
}
pets = ['jumbo','snoopy','shilla'] # created list 
for pet in pets :
print ( (pet) + " is "+ str(eval(pet)["kind"]) + " the owner is " + str(eval(pet)["owner"]) + "." )

输出:

jumbo is cat the owner is Rahma.
snoopy is dog the owner is fahad.
shilla is bird the owner is farooq.

相关内容

  • 没有找到相关文章

最新更新