這是代碼: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)

慕萊塢森
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})
添加回答
舉報
0/150
提交
取消