剛剛學(xué)習(xí)在 Python 上編碼,所以我創(chuàng)建了這個測試字典。我希望從字典中刪除輸入,但是每次在 pop 函數(shù)之后打印字典時,它都不會刪除鍵或值。我使用的是 Python 3.7.2 ShellfirstDict = {1:"five", 2:"ten", 3:"fifteen", 4:"twenty"}print(firstDict)inputKeyToDelete = input("Please enter a key whose corresponding value you wish to delete: ")if inputKeyToDelete in firstDict: firstDict.pop(inputKeyToDelete)print(firstDict)如果我輸入一個鍵(例如 2),我希望(2:"ten")從字典中刪除該鍵和值,我希望輸出為: (1:"five", 3:"fifteen", 4:"twenty")
1 回答

幕布斯7119047
TA貢獻(xiàn)1794條經(jīng)驗 獲得超8個贊
您只需使用 將輸入字符串轉(zhuǎn)換為整數(shù)即可int()
。像這樣:
inputKeyToDelete = int(input("Please enter a key whose corresponding value you wish to delete: "))
那是因為從標(biāo)準(zhǔn)輸入input()
讀取字符串。
添加回答
舉報
0/150
提交
取消