如何在Python中搜索字典

时间:2015-01-30 02:36:57

标签: python search dictionary

我是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,但我发现它没用。

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

7 个答案:

答案 0 :(得分:8)

如果您想知道key中的people是否为关键字,您可以简单地使用表达式key in people,如下所示:

if key in people:

并测试people中的

是否

if key not in people:

答案 1 :(得分:2)

足够简单

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

答案 2 :(得分:1)

你可以这样做:

#!/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))

答案 3 :(得分:0)

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

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

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

答案 4 :(得分:0)

Python还支持枚举循环遍历字典。

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

答案 5 :(得分:0)

一种可能的解决方案:

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

答案 6 :(得分:-1)

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

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

测试某些东西是否在Python中的字典中的规范方法是尝试访问它并处理失败 - It is easier to ask for forgiveness than permission (EAFP)