Search code examples
pythondictionaryuser-input

Cannot remove a value from a key in dictionary through taking input from user in python


here is the code :

dict1 = {"games" : ["football", "cricket"]}
print(dict1)

input1 = input("enter key : ")
input2 = input("enter value : ")

dict1[input1].pop(input2)

It gives output as :

'games': ['football', 'cricket']}
enter key : games
enter value : football
Traceback (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 integer
Process finished with exit code 1

it is working fine with append

dict1[input1].append(input2)

even i tried using for loop :

for key, values in dict1.items():
    values.pop(input2)

it gives error as :

{'games': ['football', 'cricket']}
enter key : games
enter value : football
Traceback (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 integer

Process finished with exit code 1

and when i use (int):

input2 = int(input("enter value : "))

it gives error as

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'

and i also used del

del dict1[input2]

it says

TypeError: 'str' object cannot be interpreted as an integer

i do not why it is interpreting it as integer


Solution

  • Dont use pop try this instead.

    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)