【问题标题】:Having trouble with python while loop and dictionarypython while循环和字典有问题
【发布时间】:2020-09-07 23:59:17
【问题描述】:

我是 python while 循环和字典的新手。

我想写一个重复提示的代码示例,提示用户输入一个键,然后是一个值。然后应该将键和值存储在字典中。

一旦用户输入单词“Done”作为键,然后输入“Done”作为值,它应该停止提示用户输入键和值。我们可以假设用户只会输入字符串类型的键和字符串类型的值。我们也不必担心重复键。

在用户键入“完成”作为值并键入“完成”作为键之后,代码示例应提示用户输入一个查找键。它将打印出该键的值并完成。

请参阅下面的示例...

例子

键:涂

值:星期二

关键:我们

值:星期三

键:Th

值:星期四

键:Fr

价值:完成

键:萨

值:星期六

关键:完成

价值:完成

你想查什么?神父

完成

我的代码(如何修复?)

a = input('Key: ')
b = input('Value: ')
dict = {a: b}
while a != 'Done' and b != 'Done':
        new_dict = {input('Key: '): input('Value: ')}
        dict.update(new_dict)
key = input('What would you like to look up?')
print(dict.get(key))

【问题讨论】:

    标签: python dictionary while-loop


    【解决方案1】:

    我认为你需要:

    d = {}
    while True:
        k = input("key: ")
        v = input("value: ")
        d[k] = v
        if k=="Done" and v=="Done":
            break
    
    x = input("What would you like to look up?")
    
    print(d.get(x))
    

    【讨论】:

      【解决方案2】:

      有几个问题需要解决:

      • 定义字典:

        d = dict() OR d = {}
        
      • 设置键值:

        d[a] = b
        
      • 我不确定您为什么需要另一个 while 嵌套循环。

      不管怎样,这里有一个例子来说明如何实现上述定义:

      d = dict()
      a = raw_input('Key: ')
      b = raw_input('Value: ')
      d[a] = b
      while a != 'Done' and b != 'Done':
          a = raw_input('Key: ')
          b = raw_input('Value: ')
          d[a] = b
      
      for k, v in d.iteritems():
          print k+":  " + v
      

      【讨论】:

        【解决方案3】:

        您可以使用get 作为while 循环的条件:

        d = {}
        while d.get('Done','') != 'Done':
            key = input('Key: ')
            val = input('Val: ')
            d[key] = val
        print(d.get(input("What would you like to look up?:"),"Not present in Dict"))
        print("Done")
        

        示例运行:

        Key: Mo
        
        Val: Monday
        
        Key: Tue
        
        Val: Tuesday
        
        Key: Done
        
        Val: Done
        
        What would you like to look up?:Mo
        Monday
        Done
        

        【讨论】:

          【解决方案4】:

          您可以使用此代码-

          dict1 = {}
          while True:
              a = input('Key: ')
              b = input('Value: ')
              dict1[a] = b
              if a == b == "Done":
                  break
          key = input('What would you like to look up?\n')
          print(dict1[key])
          

          【讨论】:

            猜你喜欢
            • 2019-03-26
            • 1970-01-01
            • 1970-01-01
            • 2023-03-14
            • 1970-01-01
            • 2020-08-18
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多