首页 > 解决方案 > 具有不同名称的字典以及如何打印名称

问题描述

宠物:制作几个字典,每个字典的名字都是宠物的名字。在每个字典中,包括动物的种类和所有者的名字。将这些字典存储在一个名为 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() + "." ) )

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

标签: pythonlistdictionaryfor-loop

解决方案


你可以eval()像下面这样使用(见参考):

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.

推荐阅读