【发布时间】:2015-03-29 11:36:07
【问题描述】:
我是 Python 字典的新手。我正在制作一个简单的程序,该程序有一个字典,其中包括四个名称作为键和相应的年龄作为值。我想要做的是,如果用户输入一个名称,程序会检查它是否在字典中,如果是,它应该显示有关该名称的信息。
这是我目前所拥有的:
def main():
people = {
"Austin" : 25,
"Martin" : 30,
"Fred" : 21,
"Saul" : 50,
}
entry = input("Write the name of the person whose age you'd like to know, or write 'ALL' to see all names and ages: ")
if entry == "ALL":
for key, value in people.items():
print ("Name: " + key)
print ("Age: " + str(value) + "\n")
elif people.insert(entry) == True:
print ("It works")
main()
我尝试使用 .index() 搜索字典,因为我知道它在列表中使用,但它没有用。我也试过检查this post,但没有发现它有用。
我需要知道是否有任何功能可以做到这一点。
【问题讨论】:
-
为什么需要函数?人[条目]
-
您可以使用以下语法在 python dict 中查找一个值:dict[key] 如果键不在字典中,则会引发 KeyError,例如people['Austin'] 或者您可以使用 get(key) 方法,如果密钥不在字典中,则返回 None ,例如people.get("Austin")
标签: python search dictionary