I am doing programming for the last 3 months, still a beginner.
I am repeatedly getting this key error on this simple code.
m = int(input("\n enter the total no. of elements in the structure 'N' "))
elements = {}
for i in range(m):
el_no = input("enter the element number:")
el_con = input("going from which node to which node:")
elements.update({el_no:el_con})
print('elements', elements)
def length(element):
# find the nodes that the elements connects
fromNode = elements[element][0]
print('fromnode',fromNode)
toNode = elements[element][1]
print('fromnode',toNode)
return fromNode, toNode
print(length(1))
as I run the file, I am getting this error. -
enter the total no. of elements in the structure 'N' 1
enter the element number:1
going from which node to which node:1,2
elements {'1': '1,2'}
Traceback (most recent call last):
File "D:\python programming\a new program 2021\testing.py", line 30, in <module>
print(length(1))
File "D:\python programming\a new program 2021\testing.py", line 20, in length
fromNode = elements[element][0]
KeyError: 1
CodePudding user response:
The input
function returns a string, while you seem to want a tuple. So you have to convert it.
Let's say that el_con
is two numbers separated by whitespace.
items = tuple(int(j) for j in el_con.split())
elements[el_no] = items
CodePudding user response:
You try to update a value for a key that is not yet in the dictionary elements
. This raises the error:
elements = {}
elements.update({"joe":42})
print(elements)
NameError: name 'joe' is not defined
You may simply insert a value associated with a key. This does not depend on the previous state of the dictionary.
elements = {}
elements["joe"] = 12
elements.update({"joe":42})
print(elements)
{'joe': 42}
To my opinion the best way to deal with this is
key = "joe"
value = 42
elements[key] = value
print(elements)
If you need to increment a value in a while loop:
if key not in elements:
elements[key] = 0
elements[key] = 1