python while循环和字典遇到问题

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

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

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

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

请参见下面的示例...

示例

  

键:涂

     

值:周二

     

键:我们

     

值:星期三

     

键:Th

     

值:星期四

     

键:Fr

     

值:完成

     

键:萨

     

值:星期六

     

键:完成

     

值:完成

     

您想查找什么? 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))
hash712 回答:python while循环和字典遇到问题

我认为您需要:

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))
,

有几处要解决的问题:

  • 定义字典:

    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
,

您可以使用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
,

您可以使用此代码-

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])
本文链接:https://www.f2er.com/3126001.html

大家都在问