python - 无法通过在 python 中获取用户的输入从字典中的键中删除值
问题描述
这是代码:
dict1 = {"games" : ["football", "cricket"]}
print(dict1)
input1 = input("enter key : ")
input2 = input("enter value : ")
dict1[input1].pop(input2)
它给出的输出为:
'games': ['football', 'cricket']}
enter key : games
enter value : football
Traceback (most recent call last):
File "C:/Users/fateo/PycharmProjects/pythonTuts/10Dictionary.py", line 116, in <module>
dict1[input1].pop(input2)
TypeError: 'str' object cannot be interpreted as an integer
Process finished with exit code 1
它与追加工作正常
dict1[input1].append(input2)
即使我尝试使用 for 循环:
for key, values in dict1.items():
values.pop(input2)
它给出的错误为:
{'games': ['football', 'cricket']}
enter key : games
enter value : football
Traceback (most recent call last):
File "C:/Users/fateo/PycharmProjects/pythonTuts/10Dictionary.py", line 113, in <module>
values.pop(input2)
TypeError: 'str' object cannot be interpreted as an integer
Process finished with exit code 1
当我使用(int)时:
input2 = int(input("enter value : "))
它给出了错误
Traceback (most recent call last):
File "C:/Users/fateo/PycharmProjects/pythonTuts/10Dictionary.py", line 110, in <module>
input2 = int(input("enter value : "))
ValueError: invalid literal for int() with base 10: 'football'
我也用过del
del dict1[input2]
它说
TypeError: 'str' object cannot be interpreted as an integer
我不知道为什么将其解释为整数
解决方案
不要改用pop
试试这个。
dict1 = {"games" : ["football", "cricket"]}
print(dict1)
input1 =input("enter key : ")
input2 = input("enter value : ")
for value in dict1.values():
if (input2) in value:
value.remove(input2)
print(dict1)
推荐阅读
- python - How to count consecutive string values of one column grouped by column values of another in a dataframe?
- java - 内置字符串方法的使用是否会创建新字符串
- excel - 在 Excel 中的二维列表中查找值并找到最后一个实例
- java - 创建二维字符串数组
- powershell - 如何从 PowerShell 中的父窗口获取后台任务状态
- node.js - 如何在打字稿中进行模块解析以输出节点?
- reactjs - React 应用程序无法访问 Apache 上的 NodeJs 后端
- python - 错误:目录迁移已经存在,并且从烧瓶数据库初始化中不为空
- docker - 通过 ssh 在远程机器上运行 docker 命令
- java - AWS JAVA SDK 错误“存储桶位于此区域:us-east-1。请使用此区域来”