What I am trying to do is make an ancestor dictionary of sorts, which I have succeeded in doing. My only problem is that when a relationship doesn't exist, my program should output "The relationship isn't in the dictionary." I know how to do that when the key is not in the dictionary, but how do I do that with the value?
Here is my code:
relationships = {"Jalen": "Joseph", "Arthur": "Joseph", "Mike": "Joseph", "Chris": "Joseph", "Joseph": "Thomas", "Jesse": "Marcus", "Marcus": "Gerhard", "Gerhard": "Allan", "Allan": "Thomas", "James": "Gerhard"}
print relationships
def menu():
print ("To find a father, press 1.")
print ("To find a grandfather, press 2.")
print ("To find a great-grandfather, press 3.")
print ("To exit the program, press 0,")
while True:
choice = input("Enter your choice of action: ")
if (choice >= 0) and (choice <= 3):
return choice
else:
print("Invalid option. Enter an integer from 0 to 3")
def father(n):
if relationships.has_key(n):
return relationships[n]
def grandfather(n):
if relationships.has_key(n):
father = relationships[n]
if relationships.has_key(father):
return relationships[father]
def greatgrandfather(n):
if relationships.has_key(n):
father = relationships[n]
if relationships.has_key(father):
grandfather = relationships[father]
if relationships.has_key(grandfather):
return relationships[grandfather]
def main ():
while True:
choice = menu()
if choice == 0:
break
else:
name = raw_input("Please enter the name of the person for whom you seek an ancestory: ")
if relationships[name]:
if choice == 1:
print "The father of ", name, " is ", father(name), "."
elif choice == 2:
print "The grandfather of ", name, " is ", grandfather(name), "."
else:
print "The great-grandfather of ", name, " is ", greatgrandfather(name), "."
else:
print "This relationship is not in our records."
main()
How would I check to see if the relationship exists in the values or not? Python language.
The in
keyword is used to check if a value or key is in a dictionary. So, all you have to do to check if a key exists in a dictionary is:
if record not in relationships:
print "This relationship is not in our records.
if aRelationship in relationships.values():
#aRelationship in relationships.values()
else:
#aRelationship not in relationships.values()
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.