为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

缥缈止盈 2023-06-27 18:07:46
这是代码:dict1 = {"games" : ["football", "cricket"]}print(dict1)input1 = input("enter key : ")input2 = input("enter value : ")dict1[input1].pop(input2)它给出的输出为:'games': ['football', 'cricket']}enter key : gamesenter value : footballTraceback (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 integerProcess finished with exit code 1它与附加一起工作正常dict1[input1].append(input2)即使我尝试使用 for 循环:for key, values in dict1.items():    values.pop(input2)它给出的错误为:{'games': ['football', 'cricket']}enter key : gamesenter value : footballTraceback (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 integerProcess 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'我也用了deldel dict1[input2]它说TypeError: 'str' object cannot be interpreted as an integer我不明白为什么它把它解释为整数
查看完整描述

3 回答

?
Smart猫小萌

TA贡献1911条经验 获得超7个赞

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


查看完整回答
反对 回复 2023-06-27
?
猛跑小猪

TA贡献1858条经验 获得超8个赞

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



查看完整回答
反对 回复 2023-06-27
?
慕莱坞森

TA贡献1810条经验 获得超4个赞

您不能使用pop带有字符串值作为参数的 on 列表。需要pop要删除的元素的索引。


因为你的字典只有一个键,所以最简单的方法就是字典理解:


{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})


查看完整回答
反对 回复 2023-06-27
  • 3 回答
  • 0 关注
  • 119 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信