我是Eric Matthes撰写的Crash Course Python的完整入门者。这是我的代码,试图访问词典密钥,并将字典存储在列表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')
答案 0 :(得分:0)
我认为您几乎可以得到想要的东西,只是忘了需要实际引用您请求的用户输入。
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']))