Hemanth Savasere Hemanth Savasere - 6 months ago 8
Python Question

Python key error in inserting

I am facing a problem in inserting operation on dictionary as given here in the code

input format

no. of operations to be performed in first line then, the operations to be performed

Error

Traceback (most recent call last):
File "solution.py", line 25, in <module>
arr.insert(cmd[j])
KeyError: ('1', '10')


Inputs

2
insert 0 5
print


CODE

arr = list()

cmd = dict()


num = int(raw_input())

for i in range(0,num):

command = str(raw_input())
command = command.split(" ")

if(len(command) == 2):
cmd[command[0]] = command[1]

if(len(command) == 3 ):
cmd[command[0]] = command[1],command[2]



for i,j in cmd.items():

if(i == "insert"):
arr.insert(cmd[j])

if(i == "append"):
arr.append(cmd[j])

if(i == "remove"):
arr.remove(cmd[j])

if(i == "pop"):
arr.pop(cmd[j])

if(i == "sort"):
arr.sort()

if(i == "index"):
print arr.index(cmd[j])

if(i == "count"):
print arr.count(cmd[j])

if(i=="print"):
print arr

Answer

Here:

     if(len(command) == 3 ):
         cmd[command[0]] = command[1],command[2]

a tuple (command[1],command[2]) is inserted in the dictionnary cmd.

Then, you sent the whole tuple as index parameter for the insert method:

   if(i == "insert"):
       arr.insert(cmd[j])

You should probably unpack it before, using first argument as index and second as object:

   if(i == "insert"):
       arr.insert(*cmd[j])

or, more verbose:

   if(i == "insert"):
       index, obj = cmd[j]
       arr.insert(index, obj)
Comments