-3

I have a question about a simple quiz which is removing a specific key from a dictionary with function. Input must be taken from user. For example:

myDict = {'a':1,'b':2,'c':3,'d':4}

keyToRemove = ‘a’

would remove the first element from the dictionary and return the result.

I have developed such a code, but when I type 'a' it doesn't work. When I type only a it is removed. Could you help me to solve this question?

myDict = {'a':1,'b':2,'c':3,'d':4}
def key_Remover(Dict):
  x = input("Please enter dictionary key to remove: ")
  del Dict[x]
  return Dict


key_Remover(myDict)
print(myDict)
jonrsharpe
  • 115,751
  • 26
  • 228
  • 437
  • https://stackoverflow.com/questions/11277432/how-can-i-remove-a-key-from-a-python-dictionary – starboy_jb Dec 20 '21 at 10:31
  • 3
    the actual key is letter `a`, `'a'` is just how python displays strings. – luk2302 Dec 20 '21 at 10:31
  • Does this answer your question? [How can I remove a key from a Python dictionary?](https://stackoverflow.com/questions/11277432/how-can-i-remove-a-key-from-a-python-dictionary) – Abdur Rakib Dec 20 '21 at 10:32
  • print repr(x) just before the del. you may have some cleanup to do. – Abel Dec 20 '21 at 10:32
  • 1
    Quotes are valid string characters as well. When you enter 'a' it gets read as \'a\' which does not match the main key a. When you use input() the quotes are implied within code as that is how they are demarcated in Python strings – fibonachoceres Dec 20 '21 at 10:32

1 Answers1

0

input takes the user input as a string. If the user puts in a and hits enter, the input string is 'a'. If the user puts in 'a' and hits enter, the input string is "'a'".

'a' exists in your dictionary, "'a'" does not.

actual_panda
  • 1,178
  • 9
  • 27
  • Yes I realized that, but I didn't know how to do this like in the example. Because that is what the instructor wants. – Lucas Merten Dec 20 '21 at 10:34
  • @LucasMerten Are you sure your instructor wants the user to enter the key with quotes around it? That seems a strange requirement. Have you checked why they want that? – kaya3 Dec 20 '21 at 10:36
  • Yes, I am sure. I pasted exact same question as an example. – Lucas Merten Dec 20 '21 at 10:38