我是 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,但我发现它没有用。
我需要知道是否有任何函数可以做到这一点。
最佳答案
如果您想知道 key
是否是 people
中的键,您可以简单地使用表达式 key in people
,如下所示:
if key in people:
并测试它是否不是 people
中的键:
if key not in people:
关于python - 如何查字典?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28228345/