python - 如何将输入字符串附加到字典键 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)
解决方案
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)
推荐阅读
- javascript - Node.js API 对不同 Recipient 的响应
- .htaccess - 如何允许来自 HTTP_REFERER 的引用并且不在 htaccess 中阻止 HTTP_USER_AGENT?
- python - 覆盖 Map 中使用的函数的默认参数
- r - ggplot2 两个填充两个不同的变量
- android-pdf-api - AndroidPdfViewer 在 KitKat 版本中不起作用
- matlab - 使用 textscan 将制表位读取为 4 个空格
- c# - 使用 Angular 6 将文件上传到 Web Api C#
- java - 从 Spring 上下文中获取一个 bean(以编程方式注册)?
- kotlin - 在 Kotlin 中的 when 语句中检查几种类型
- nuget - VS2017“恢复包”恢复了80个包。"nuget.exe restore" 恢复 64 个包