【问题标题】:How can I create a dictionary and output values using user input?如何使用用户输入创建字典和输出值?
【发布时间】:2016-02-21 06:22:25
【问题描述】:

我想制作一个字典,然后使用用户输入来打印键的值

编辑:我使用的是 Python 3.4.4 并感谢纠正语法和句法错误的用户

*我尝试使用 -input()- 但没有运气 *我找到了这段代码:

usrInp = 'z' #default value z so that while works first time
exDict = {}  #initializing empty dict

while usrInp == 'z':
    key = input('enter key : ')
    val = input('enter val : ')
    exDict[key] = val
    usrInp = input('Enter z to continue adding, else any input to exit : ')

print(exDict)

但这不是我想要的。我的目标是做这样的事情:

 dictionary{
     1:"Number one"
     2:"Number two"
     3:"Number three"
}

#Asking for user input code here

print() #Print the value of the key here

【问题讨论】:

    标签: python dictionary output user-input


    【解决方案1】:

    试试这个:

    dictionary={
     "1":"Number one"
     "2":"Number two"
     "3":"Number three"}
    
    x = raw_input()
    print dictionary[str(x)]
    

    【讨论】:

      【解决方案2】:

      试试这个

      usrInp = 'z' #默认值 z 以便在第一次工作时 exDict = {} #初始化空字典 而 usrInp == 'z': key = input('输入键:')) val = input('输入 val : ')) exDict[key] = val usrInp = input('输入z继续添加,否则任何输入退出:') 打印(exDict)

      【讨论】:

      • 感谢您的帮助,但此代码无需转换即可运行
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-09-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多