python - 访问字典中的部分值
问题描述
得到一个任务来编写一个程序,该程序根据用户输入的整数对给定字典执行操作
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,我该如何只访问值的一部分?
解决方案
您的语法会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
推荐阅读
- javascript - 如何在客户端点击时查询 mongodb 的现有数据?
- google-apps-script - 谷歌表格复制一个单元格并粘贴到另一个单元格
- javascript - 如何通过单击按钮从已处理的 PHP 页面调用 PHP 函数?
- python - 计算两个数据框中一列的平均值,然后在带有特定标签的条形图中绘制每个数据框的平均值?
- python - request.form 转换为字典时仅返回第一个值
- apache-kafka - 将日志从 Kafka 发送到 ClickHouse 时获取空行
- php - 为什么这个 get 函数不接收变量 car?
- laravel - 在 Laravel auth 中,该路由不支持 POST 方法。支持的方法:GET、HEAD
- .htaccess - .htaccess - 添加 www。& 删除 .html
- reactjs - Jest spyOn 无法处理从另一个文件导入函数的 React 功能组件