Python 如何通过字典进行搜索?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/28228345/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 02:57:38  来源:igfitidea点击:

How to search through dictionaries?

pythonsearchdictionary

提问by Fede Couti

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.

我是 Python 词典的新手。我正在制作一个简单的程序,它有一个字典,其中包含四个名称作为键和相应的年龄作为值。我想要做的是,如果用户输入一个名字,程序会检查它是否在字典中,如果是,它应该显示有关该名字的信息。

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

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 postbut I didn't find it useful.

我尝试在字典中搜索,.index()因为我知道它在列表中使用过,但没有用。我也试过检查这篇文章,但我发现它没有用。

I need to know if there is any function that can do this.

我需要知道是否有任何功能可以做到这一点。

采纳答案by Scott Hunter

If you want to know if keyis a key in people, you can simple use the expression key in people, as in:

如果你想知道 ifkey是一个键people,你可以简单地使用表达式key in people,如:

if key in people:

And to test if it is nota key in people:

并测试它是否不是一个键people

if key not in people:

回答by Laurent Jalbert Simard

Simple enough

足够简单

if entry in people:
    print ("Name: " + entry)
    print ("Age: " + str(people[entry]) + "\n")

回答by Games Brainiac

You can reference the values directly. For example:

您可以直接引用这些值。例如:

>>> people = {
... "Austun": 25,
... "Martin": 30}
>>> people["Austun"]

Or you can use people.get(<Some Person>, <value if not found>).

或者你可以使用people.get(<Some Person>, <value if not found>).

回答by Cui Heng

Python also support enumerate to loop over the dict.

Python 还支持 enumerate 循环遍历 dict。

for index, key in enumerate(people):
    print index, key, people[key]

回答by Guilherme Arthur de Carvalho

You can make this:

你可以这样做:

#!/usr/bin/env python3    

people = {
    'guilherme': 20,
    'spike': 5
}

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 in people.keys():
        print ('Name: {} Age: {}'.format(key, people[key]))

if entry in people:
    print ('{} has {} years old.'.format(entry, people[entry]))
else:
    # you can to create a new registry or show error warning message here.
    print('Not found {}.'.format(entry))

回答by D.Shawley

Of all of the answers here, why not:

在这里的所有答案中,为什么不:

try:
    age = people[person_name]
except KeyError:
    print('{0} is not in dictionary.'.format(person_name))

The canonical way to test if something is in a dictionary in Python is to try to access it and handle the failure -- It is easier to ask for forgiveness than permission (EAFP).

测试某些东西是否在 Python 字典中的规范方法是尝试访问它并处理失败——请求宽恕比请求许可 (EAFP) 更容易

回答by Muhammad Umar

One possible solution:

一种可能的解决方案:

people = {"Austin" : 25,"Martin" : 30,"Fred" : 21,"Saul" : 50,}

entry =raw_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 in people.keys():
        print(people[key])

else:

    if entry in people:
        print(people[entry])