得到一个任务,编写一个程序,根据用户输入的整数对给定的字典执行操作
Celebrity = {"first_name": "Mariah", "last_name": "Carey", "birth_date": "27.03.1970", "hobbies": ["sing", "compose", "act"]}
如果用户输入是2,程序应该打印玛丽亚的出生月份(字符串的"3"部分(。如果用户输入是4,则程序应该打印列表上的最后一个爱好("动作"(。
我试过了:
user_input = input ("Please enter a number between 1 and 8: ")
if int(user_input) == 2:
print(Celebrity["birth_date"[4:5])
if int(user_input) == 4:
print (Celebrity["hobbies"[2]])
这两个条件最终都会给我KeyErrors,我该如何只访问值的一部分?
您的语法是Celebrity["birthdate"[4:5])
,它会产生错误。用CCD_ 2改变它。并且CCD_ 3也用CCD_。
试试这个:
Celebrity = {"first_name": "Mariah", "last_name": "Carey", "birth_date": "27.03.1970", "hobbies": ["sing", "compose", "act"]}
user_input = input ("Please enter a number between 1 and 8: ")
if int(user_input) == 2:
print(Celebrity["birth_date"][4:5])
if int(user_input) == 4:
print (Celebrity["hobbies"][2])
输出:
Please enter a number between 1 and 8: 2
3
Please enter a number between 1 and 8: 4
act
给你;
Celebrity = {"first_name": "Mariah", "last_name": "Carey", "birth_date": "27.03.1970", "hobbies": ["sing", "compose", "act"]}
user_input = input ("Please enter a number between 1 and 8: ")
if int(user_input) == 2:
print(Celebrity["birth_date"][4:5])
if int(user_input) == 4:
print (Celebrity["hobbies"][2])
你把括号放错了地方,然后这些地方就变成了";h〃;以及";b";从";生日_日期";以及";爱好;作为密钥。
当您想要获得值时,您需要使用方括号中的键。如果您想要只获取装载,您可以通过索引获取值。如果你想得到数组中的最后一个值,你可以像这个Celebrity["hobbies"][-1]
一样使用索引-1
Celebrity = {"first_name": "Mariah", "last_name": "Carey", "birth_date": "27.03.1970", "hobbies": ["sing", "compose", "act"]}
user_input = input ("Please enter a number between 1 and 8: ")
if int(user_input) == 2:
print(Celebrity["birth_date"][4])
if int(user_input) == 4:
print (Celebrity["hobbies"][-1])