'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.
Solution 1:[1]
Simple enough
if entry in people:
print ("Name: " + entry)
print ("Age: " + str(people[entry]) + "\n")
Solution 2:[2]
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>).
Solution 3:[3]
Python also support enumerate to loop over the dict.
for index, key in enumerate(people):
print index, key, people[key]
Solution 4:[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))
Solution 5:[5]
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).
Solution 6:[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])
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Laurent Jalbert Simard |
| Solution 2 | Games Brainiac |
| Solution 3 | Cui Heng |
| Solution 4 | Guilherme Arthur de Carvalho |
| Solution 5 | D.Shawley |
| Solution 6 |
