python - 如何从存储在列表中的字典中正确访问字典键?
问题描述
我是一个完整的初学者阅读 Eric Matthes 的 Crash Course Python。这是我尝试访问字典键的代码,字典存储在 list 中shirts
。
red_shirt = {'shirt_color': 'red', 'shirt_price': 20}
blue_shirt = {'shirt_color': 'blue', 'shirt_price': 25}
green_shirt = {'shirt_color': 'green', 'shirt_price': 30}
shirts = [red_shirt, blue_shirt, green_shirt]
user_input = input('Which shirt would you like to purchase?\n:')
for shirt in shirts:
到目前为止,我相信我的for
循环有问题......我应该使用第二个for
循环来访问字典中的键吗?
if shirt['shirt_color'] == 'red':
#shirt_color = 'red'
print('You bought the ' + shirt['shirt_color'] + ' shirt for $' + str(shirt['shirt_price']))
与使用k['v']
来访问字典的值相反,我也尝试过使用.format
.
elif shirt['shirt_color'] == 'blue':
#shirt_color = 'blue'
print('You bought the ' + shirt['shirt_color'] + ' shirt for $' + str(shirt['shirt_price']))
elif shirt['shirt_color'] == 'green':
#shirt_color = 'green'
print('You bought the ' + shirt['shirt_color'] + ' shirt for $' + str(shirt['shirt_price']))
else:
print('It seems we do not have the shirt you are looking for, please try again')
解决方案
我想你几乎得到了你想要的,你只是忘记了你需要实际引用你请求的用户输入。
red_shirt = {'shirt_color': 'red', 'shirt_price': 20}
blue_shirt = {'shirt_color': 'blue', 'shirt_price': 25}
green_shirt = {'shirt_color': 'green', 'shirt_price': 30}
shirts = [red_shirt, blue_shirt, green_shirt]
user_input = input('Which shirt would you like to purchase?\n:')
for shirt in shirts:
if shirt['shirt_color'] == user_input:
print('You bought the ' + shirt['shirt_color'] + ' shirt for $' + str(shirt['shirt_price']))
推荐阅读
- php - 如果值与函数匹配,我如何从下拉列表中选择值?
- python - 我想在 django 的 view_project.html 页面中显示用户输入的所有数据
- makefile - 使用 Makefile 中的模式自定义目标
- angular - [(ngModel)]='products.title' 问题 // 类型 '{}' 上不存在属性 'title'
- powershell - 类成员被 json 序列化为空字符串而不是 null
- sql - Azure 中的 SQL 服务器:内部连接相当于此处的左连接?
- elasticsearch - Elasticsearch,elasticsearch.keystore 使用哪个路径?
- python - 您如何在 Ctypes 中指定从 python 到 C 的变量类型?
- kotlin - IDE 对 Dispatchers.IO 协程中的阻塞调用发出警告
- r - 无法在 R Markdown 中计算 t 检验函数