我想要做的是制作一个祖先的字典,我已经成功了。我唯一的问题是,当一段关系不存在时,我的程序应该输出"关系不在字典中。"当密钥不在字典中时,我知道如何做到这一点,但是如何使用值?
这是我的代码:
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()
我如何检查值中是否存在关系? Python语言。
答案 0 :(得分:1)
in
关键字用于检查值或键是否在字典中。因此,您需要做的就是检查字典中是否存在密钥:
if record not in relationships:
print "This relationship is not in our records.
答案 1 :(得分:0)
我不知道正在引发哪个错误,但我认为这是一个KeyError,在这一行中
if relationships[name]:
如果不存在关系[name],则会引发异常。 更好的代码是使用
if relationships.get(name, ''):
这样,如果name
不在字典中,它就不会读取if statement
内的代码。
如评论中所述,另一种方法是
if name in relationships:
答案 2 :(得分:0)
if aRelationship in relationships.values():
#aRelationship in relationships.values()
else:
#aRelationship not in relationships.values()