[英]How to properly access dictionary keys from dictionaries stored in list?
I am a complete beginner reading Crash Course Python by Eric Matthes. 我是Eric Matthes撰写的Crash Course Python的完整入门者。 Here is my code trying to access a dictionary key, with the dictionaries stored within the list shirts
. 这里是我的代码试图访问一个辞典键,用字典存储在列表中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:
So far I believe I have an issue with the for
loop... Should I be using a second for
loop to access the keys within the dictionary? 到目前为止,我相信我的for
循环有问题...是否应该使用第二个for
循环来访问字典中的键?
if shirt['shirt_color'] == 'red':
#shirt_color = 'red'
print('You bought the ' + shirt['shirt_color'] + ' shirt for $' + str(shirt['shirt_price']))
Opposed to using k['v']
to access the values of the dictionary, I have also tried using .format
. 与使用k['v']
访问字典的值.format
,我也尝试使用.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')
I think you almost got what you wanted, you just forgot that you needed to actually reference the user input you requested. 我认为您几乎可以满足您的要求,而只是忘记了需要实际引用您所请求的用户输入。
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']))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.