the objective is to find the common element of the two array
here error comes when dictionary is inputted with values not present in the list A.
import numpy as np
A=np.random.randint(1,10,15)
B=np.random.randint(1,15,15)
print(A)
print(B)
dic={}
for x in A:
dic[x]=1
for y in B:
if dic[y]!=None:
print("the common element is ", y)
I know there are ways like set, for and if, methods to do this. I am just curious whether the above code can be made to work.
Here i am aiming for finding the common elements in two lists.
the values of the first list is used to set keys of the dictionary.
the code crashes at this point — if dic[y]!=None:
is there any way by which we can make this code work?
>Solution :
When dictionary[key] is called but the key doesn’t exist, it raises a KeyError, which terminates your program unless you catch it with try and except. An alternative is using dictionary.get(key), which returns None in the case of a missing key.