0

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?

JonSG
  • 10,542
  • 2
  • 25
  • 36
  • 2
    Does this answer your question? [Why dict.get(key) instead of dict\[key\]?](https://stackoverflow.com/questions/11041405/why-dict-getkey-instead-of-dictkey) – slothrop Jul 13 '23 at 16:17
  • Given that your ultimate objective is to find values that are common to both lists, have you considered using sets? – DarkKnight Jul 13 '23 at 16:38

2 Answers2

0

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.

Daniel Li
  • 16
  • 4
  • Using dict.get() and testing for None will work in this particular case but don't forget that it's not a general solution as a key might exist with a value of None – DarkKnight Jul 13 '23 at 17:16
0

As the dictionary is constructed with pseudo-random keys with 1 as their associated value, it is reasonable to use dict.get() in this case. That's because if dict.get() returns None then you can assert that the key is absent.

However, that is not a general solution. Don't forget that None is a valid value. Therefore, using dict.get() doesn't necessarily inform you of the existence (or otherwise) of a key.

Here's a more robust approach:

import numpy as np

A = np.random.randint(1,10,15)
B = np.random.randint(1,15,15)

d = {n: 1 for n in A}

for y in B:
    if y in d:
        print(f'Common element {y}')

Output (sample):

Common element 5
Common element 3
Common element 2
Common element 1
Common element 3
Common element 5

Notice how in this case the values 5 and 3 are repeated in the output. Whilst it is true that they are common in both lists (actually numpy.ndarray) it doesn't really make sense to repeat them.

An improved approach would be to look at the intersection of two sets as follows:

print(set(A) & set(B))

... which, in this case gives:

{1, 2, 3, 5}
DarkKnight
  • 19,739
  • 3
  • 6
  • 22