简体   繁体   English

在Python中从Dictionary删除键

[英]Deleting a key from Dictionary in Python

I am trying to delete a key from a dictionary but my code doesn't delete anything. 我正在尝试从字典中删除键,但是我的代码没有删除任何内容。 Also it seems just ignoring the if statement. 而且似乎只是忽略了if语句。

Thanks for the help guys 谢谢你们的帮助

Here is my code: 这是我的代码:

empVar={}
empVar[25]="square of 5"
empVar.update({3:9})
print(empVar)
print(empVar.keys())
print(empVar.values())

keyValToDel=input("Enter key to del: ")
if keyValToDel in empVar:
    empVar.pop(keyValToDel)
    print("deleted Var: " + keyValToDel)
print(empVar)

you need to convert the input from str to int because "3" is not 3. 您需要将输入从str转换为int,因为“ 3”不是3。

empVar={}
empVar[25]="square of 5"
empVar.update({3:9})
print(empVar)
print(empVar.keys())
print(empVar.values())

keyValToDel=input("Enter key to del: ")
if int(keyValToDel) in empVar:
    empVar.pop(int(keyValToDel))
    print("deleted Var: " + keyValToDel)
print(empVar)

The input function returns a string. input函数返回一个字符串。 Your dictionary's key is an integer, so you need to cast the input's result into an int before deleting the key: 字典的键是一个整数,因此您需要在删除键之前将输入的结果转换为int

keyValToDel=int(input("Enter key to del: "))

The error you are facing is because an int can't be equal to a string in Python. 您面临的错误是因为int不能等于Python中的字符串。 You need to type case your inputs, to validate them. 您需要输入大小写,以对其进行验证。

empVar={}
empVar[25]="square of 5"
empVar.update({9:'square of 3'})

keyValToDel=int(input("Enter key to del: "))
del(empVar[keyValToDel])
print(empVar)

Thanks for the answers guys. 谢谢你们的答案。 Its my first time learning coding so what can I search to understand more about why is this the case? 这是我第一次学习编码,所以我可以搜索什么以进一步了解为什么会出现这种情况? btw I edited my code to this and it works :) 顺便说一句,我编辑我的代码,它的工作:)

empVar={}
empVar[25]="square of 5"
empVar.update({3:9})
print(empVar)
print(empVar.keys())
print(empVar.values())

keyValToDel=input("Enter key to del: ")
keyValToDel = int(keyValToDel)
if int(keyValToDel) in empVar:
   empVar.pop(keyValToDel)
   print("deleted " + str(keyValToDel))
print(empVar)enter code here

I hope this helps. 我希望这有帮助。 In python 2.7 you to do this tweak as you need to convert into to str for printing with + sign. 在python 2.7中,您需要进行此调整,因为您需要将其转换为str以使用+符号进行打印。

empVar={} 
empVar[25]="square of 5" 
empVar.update({3:9}) 
print(empVar) 
print(empVar.keys()) 
print(empVar.values()) 
keyValToDel=input("Enter key to del: ")
if keyValToDel in empVar: 
    empVar.pop(keyValToDel) 
    print("deleted Var: " + str(keyValToDel)) 
    print(empVar)

Hope your problem is solved. 希望您的问题得到解决。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM