字典内的字典调用

2024-05-20 12:28:45 发布

您现在位置:Python中文网/ 问答频道 /正文

因此,我试图调用字典中的字典,并使用键作为值,但我每次尝试都失败了。这就是我的位置,注意if表达式之后的所有print语句都失败了。你知道吗

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()

Tags: nameinorgimagewikiwikipediafileen
2条回答

当您这样做时:

print(d2(animal["name"]), "is the common name")

表示将d2视为函数。相反,试试看

animal_dict = d2.get(animal, {})
animal_name = animal_dict.get("name")
print("%s is the common name" % animal_name)

以此类推。。你知道吗

这很简单,托特。看。。。你知道吗

print(d2(animal["name"]), "is the common name")

这意味着“打印调用d2(将单个参数作为animal中的索引"name"处的对象)和字符串"is the common name"的返回值”。你知道吗

这毫无意义,不是吗?不能使用括号(call操作符())来“调用”字典。这对你有意义吗?IHMO,这没道理。你知道吗

相反,应该用键animal索引字典。但是,从评论看来,你试过这个。。。你知道吗

 d2[animal["name"]]

这意味着:“在索引处的对象(在"name"索引处的对象在animal)在d2”。再说一次,这毫无意义。正确的方法是。。。你知道吗

 d2[animal]["name"]

这意味着“在d2的索引animal中的索引"name"中的对象”。现在,这是有道理的!您应该对所有print语句应用相同的更改模式。你知道吗

为什么会这样?d2是一部词典词典。因此。。。你知道吗

x = d2[animal]

意思是“将对象存储在animald2x索引处”。然后。。。你知道吗

x["name"]

表示“x中索引"name"处的对象”。你觉得这有道理吗?;). 你知道吗

编辑:对于那些被历史原因误导的人,(几乎)永远不要在python2.x中使用input(),除非你知道自己在做什么!改用raw_input()(相同接口)。你知道吗

我希望这能给你一些启示!你知道吗

相关问题 更多 >