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.
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.
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.
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.
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:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With