我是 python while 循环和字典的新手。
我想编写一个代码示例,反复提示用户输入键和值。然后应将键和值存储在字典中。
一旦用户输入单词“Done”作为键,然后输入“Done”作为值,它应该停止提示用户输入键和值。我们可以假设用户只会输入字符串类型的键和字符串类型的值。我们也不需要担心重复键。
在用户为值键入“完成”并为键键入“完成”后,代码示例应提示用户输入一个查找键。它将打印出该键的值并完成。
请参阅下面的示例...
例子
Key: Tu
Value: Tuesday
Key: We
Value: Wednesday
Key: Th
Value: Thursday
Key: Fr
Value: Done
Key: Sa
Value: Saturday
Key: Done
Value: Done
What would you like to look up? Fr
Done
我的代码(如何修复?):
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))
最佳答案
我认为你需要:
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))
关于python - 在使用 python while 循环和字典时遇到问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58796927/