无法通过 python 中的用户输入从字典中的键中删除值

Cannot remove a value from a key in dictionary through taking input from user in 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

它与 append

一起工作正常
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

我不明白为什么将其解释为整数

您不能在以字符串值作为参数的列表上使用 poppop 需要要删除的元素的索引。

因为你的字典只有一个键,所以最简单的方法是 dictionary-comprehension:

{k: [x for x in v if x != input2] for k, v in dict1.items() if k == input1}

..你的例子里面看起来像:

dict1 = {"games" : ["football", "cricket"]}
print(dict1)

input1 = input("enter key : ")
input2 = input("enter value : ")

print({k: [x for x in v if x != input2] for k, v in dict1.items() if k == input1})

不要使用 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)

对于pop(),你应该给出索引,而不是键。即使是 del 语句也应该与索引一起 giben。改为使用 remove()