Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

what to do to ignore the output when undefined keys are inputted in python dictionary

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading