How to search through dictionaries?

橙三吉。 提交于 2019-12-24 04:27:30

问题


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

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.


回答1:


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

if key in people:

And to test if it is not a key in people:

if key not in people:



回答2:


Simple enough

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



回答3:


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




回答4:


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



回答5:


Python also support enumerate to loop over the dict.

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



回答6:


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



回答7:


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



来源:https://stackoverflow.com/questions/28228345/how-to-search-through-dictionaries

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!