如何搜索字典? [英] How to search through dictionaries?
问题描述
我是Python字典的新手.我正在制作一个简单的程序,它的字典包含四个名称作为键,相应的年龄作为值.我要尝试做的是,如果用户输入一个名称,程序将检查它是否在字典中,如果存在,它应该显示有关该名称的信息.
I'm new to Python dictionaries. I'm making a simple program that has a dictionary that includes four names as keys and the respective ages as values. What I'm trying to do is that if the user enters the a name, the program checks if it's in the dictionary and if it is, it should show the information about that name.
这是我到目前为止所拥有的:
This is what I have so far:
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()
搜索字典,因为我知道它已在列表中使用,但没有用.我还尝试检查这篇文章,但我没有发现它有用
I tried searching through the dictionary using .index()
as I know it's used in lists but it didn't work. I also tried checking this post but I didn't find it useful.
我需要知道是否有任何功能可以做到这一点.
I need to know if there is any function that can do this.
推荐答案
如果您想知道 key
是否是 people
中的键,则可以简单地使用表达式输入人物
,例如:
If you want to know if key
is a key in people
, you can simply use the expression key in people
, as in:
if key in people:
并测试它是否不是 people
中的键:
And to test if it is not a key in people
:
if key not in people:
这篇关于如何搜索字典?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!