Python - 通过键显示值的字典

时间:2018-04-27 03:29:59

标签: python dictionary output display

以下程序:

spanishdays = { 'Sunday':'Domingo', 'Monday':'Lunes', \
                'Tuesday':'Martes', 'Wednesday':'Miercoles', \
                'Thursday':'Jueves', 'Friday':'Viernes', \
                'Saturday':'Sabado' }

ui = input("Enter 'Sunday', 'Monday', 'Tuesday', 'Wednesday'," \
            "'Thursday', 'Friday', 'Saturday': ")

for ui in spanishdays:
    print('The word for ' + ui + ' in Spanish is ' + spanishdays[ui])

我认为输出结果是:如果用户输入星期一,那么“西班牙语星期一的单词是Lunes。”

但是,当我运行程序时,我得到以下输出:

Enter 'Sunday', 'Monday', 'Tuesday', 'Wednesday','Thursday', 'Friday',
'Saturday': Monday
The word for Sunday in Spanish is Domingo
The word for Monday in Spanish is Lunes
The word for Tuesday in Spanish is Martes
The word for Wednesday in Spanish is Miercoles
The word for Thursday in Spanish is Jueves
The word for Friday in Spanish is Viernes
The word for Saturday in Spanish is Sabado

我如何得到:

The word for Monday in Spanish is Lunes

2 个答案:

答案 0 :(得分:2)

您不需要循环来打印与字典中的键对应的值。

只需使用ui即可返回与spanishdays字典中的密钥spanishdays.get(ui)对应的值。或者,您可以使用KeyError来实现相同目的但从不提出spanishdays = { 'Sunday':'Domingo', 'Monday':'Lunes', \ 'Tuesday':'Martes', 'Wednesday':'Miercoles', \ 'Thursday':'Jueves', 'Friday':'Viernes', \ 'Saturday':'Sabado' } ui = input("Enter 'Sunday', 'Monday', 'Tuesday', 'Wednesday'," \ "'Thursday', 'Friday', 'Saturday': ") print('The word for ' + ui + ' in Spanish is ' + spanishdays[ui]) # Enter 'Sunday', 'Monday', 'Tuesday', 'Wednesday','Thursday', 'Friday', 'Saturday': Monday # The word for Monday in Spanish is Lunes

[ReflectionException]
  Class Magento\Framework\Intl\NumberFormatterFactory does not exist


[ReflectionException]
  Class Magento\Framework\Intl\NumberFormatterFactory does not exist


  [Magento\Framework\Exception\LocalizedException]
  Source class "\Magento\Framework\Intl\NumberFormatter" for "Magento\Framework\Intl\NumberFormatterFactory" generation doe
  s not exist.

答案 1 :(得分:0)

不需要for循环,因为您只想为dict

获取一个值
Python 3.6.5 (default, Mar 30 2018, 06:42:10)
Type 'copyright', 'credits' or 'license' for more information
IPython 6.3.1 -- An enhanced Interactive Python. Type '?' for help.

In [1]: spanishdays = { 'Sunday':'Domingo', 'Monday':'Lunes', \
   ...:                 'Tuesday':'Martes', 'Wednesday':'Miercoles', \
   ...:                 'Thursday':'Jueves', 'Friday':'Viernes', \
   ...:                 'Saturday':'Sabado' }

In [2]: ui = input("Enter 'Sunday', 'Monday', 'Tuesday', 'Wednesday',""'Thursday', 'Friday', 'Saturday': ")
Enter 'Sunday', 'Monday', 'Tuesday', 'Wednesday','Thursday', 'Friday', 'Saturday': Monday

In [3]: print('The word for %s in Spanish is %s '% (ui, spanishdays.get(ui, 'Invalid entry')))
The word for Monday in Spanish is Lunes

In [4]: