首页 > 解决方案 > 如何从存储在列表中的字典中正确访问字典键?

问题描述

我是一个完整的初学者阅读 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')

标签: python

解决方案


我想你几乎得到了你想要的,你只是忘记了你需要实际引用你请求的用户输入。

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']))

推荐阅读