python - 在使用 python while 循环和字典时遇到问题

标签 python dictionary while-loop

我是 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/

相关文章:

python - 重新排列行值

javascript - 使用谷歌地图获取纬度和经度

java - while循环与mysql java数据库

python - Django sitemap.xml - 它在哪里?

python - 无法将 Pandas Dataframe 列转换为 float

python - 使用 PyOpenGL 从索引缓冲区渲染框出现问题

python - 访问 dict 键,如果不存在则返回 None

python - 从python中的字典制作表格

c - 读取文件时使用 realloc()

python - 在 while 循环中使用条件语句