首页 > 解决方案 > 访问字典中的部分值

问题描述

得到一个任务来编写一个程序,该程序根据用户输入的整数对给定字典执行操作

Celebrity = {"first_name": "Mariah", "last_name": "Carey", "birth_date": "27.03.1970", "hobbies": ["sing", "compose", "act"]}

如果用户输入是 2,则程序应该打印 Maria 的出生月份(“3” - 字符串的一部分)。如果用户输入是 4,则程序应该打印列表中的最后一个爱好(“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]])

这两种情况最终都会给我 KeyErrors,我该如何只访问值的一部分?

标签: pythondictionary

解决方案


您的语法会Celebrity["birthdate"[4:5])产生错误。更改它Celebrity["birth_date"][4:5]。并Celebrity['hobbies[2]']创建错误更改它Celebrity["hobbies"][2]

尝试这个 :

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

推荐阅读