亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

無法通過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 關注
  • 224 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號