Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to search through dictionaries?

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.

like image 978
Fede Couti Avatar asked Jan 30 '15 02:01

Fede Couti


People also ask

How do I find something in a dictionary Python?

To simply check if a key exists in a Python dictionary you can use the in operator to search through the dictionary keys like this: pets = {'cats': 1, 'dogs': 2, 'fish': 3} if 'dogs' in pets: print('Dogs found!') # Dogs found! A dictionary can be a convenient data structure for counting the occurrence of items.

How do you iterate through a dictionary list?

In Python, to iterate the dictionary ( dict ) with a for loop, use keys() , values() , items() methods. You can also get a list of all keys and values in the dictionary with those methods and list() . Use the following dictionary as an example. You can iterate keys by using the dictionary object directly in a for loop.

Can you iterate through a dictionary Python?

Python Iterate Through Dictionary. You can iterate through a Python dictionary using the keys(), items(), and values() methods. keys() returns an iterable list of dictionary keys. items() returns the key-value pairs in a dictionary.


1 Answers

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:

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

if key not in people:
like image 128
Scott Hunter Avatar answered Oct 07 '22 17:10

Scott Hunter