【发布时间】:2015-11-08 05:48:46
【问题描述】:
所以我试图在字典中调用字典并将键用作值,但到目前为止,我每次尝试都失败了。这就是我所在的地方,请注意 if 表达式之后的所有打印语句都会失败。
def main():
print("This program tells you about the animal of your choice")
animal=input("What animal would you like to look up: ")
animal=animal.lower()
d2={
"lion":{"name":"Lion","species":"Panthera leo",
"image":"http://en.wikipedia.org/wiki/File:Lion_waiting_in_Namibia.jpg",
"fact":"Vulnerable species"},
"dog":{"name:":"Dog","species":"Canis lupus familiaris",
"image":"http://en.wikipedia.org/wiki/File:YellowLabradorLooking_new.jpg",
"fact":"Common house pet"},
"hippo":{"name":"Hippo","species":"Hippopotamus amphibius",
"image":"https://en.wikipedia.org/wiki/Hippopotamus#/media/File:Hippopotamus_-_04.jpg",
"fact":"Erbivorous mammal"},
"cat":{"name":"Cat","species":"Felis catus",
"image":"https://en.wikipedia.org/wiki/Cat#/media/File:Cat_poster_1.jpg",
"fact":"Purring hunters"}
}
if animal in d2:
print(d2(animal["name"]), "is the common name")
print(d2(animal["species"]), "is its latin name")
print(d2(animal["image"]), "is a picture of", animal)
print(d2(animal["fact"]),)
else:
print("Not in dicionary, try lion, dog, hippo, or cat")
main()
【问题讨论】:
-
一些缩进在我粘贴代码时消失了,这就是为什么文本在 d2 中看起来如此混乱
-
dict元素由[]访问,而不是()。 -
您是否注意到您使用圆括号而不是方括号来访问字典?
-
动物周围的括号仍然给出这个错误:TypeError:字符串索引必须是整数
标签: python python-2.7 python-3.x dictionary