首页 > 解决方案 > 如何将输入字符串附加到字典键 int 中?

问题描述

我正在尝试使以下代码提示答案,然后将该答案添加到名为 poll 的字典中。我正在尝试通常用于列表的附加命令,但它不仅适用于字典。

目前,我既没有设法更新键值(我的预期目标),也没有设法将新项目添加到字典中(非预期)。

poll = {
    'cat': 0,
    'dog': 0,
    'both': 0,
    'none': 0,
    }

prompt = "Are you a cat owner, dog owner, both, or none? "
prompt += "\nEnter 'quit' to stop this loop \n"
message = ""
while message != "quit":
    message = input(prompt)
    poll[message].append(value)
    if message != "quit":
        print("Your answer was submitted! \n")

print("Poll results:\n", poll)

标签: pythonpython-3.x

解决方案


If you want to add a new key-value pair to the dictionary, instead of appending you can do the following, although I do not see a variable value in your code. It will also update the value of existing key if entered again because dictionary cannot have duplicate keys

poll[message] = value

Assuming you take care of the variable value, the code will look like

As pointed out by David Buck, you need to move the poll[message] = value part inside the if statement

while message != "quit":
    message = input(prompt)
    if message != "quit":
        poll[message] = value
        print("Your answer was submitted! \n")

print("Poll results:\n", poll)

推荐阅读