-1

I am trying to make a dictionary to keep account of what values from array 1 are present in array 2 in order to locate any missing values, and then print the dictionary.

I keep getting the following error:

KeyError: 1 at 'count[x] += 1'

I can't make sense of it. I am a beginner to data structures and I'd appreciate any help.

Here is what I have written:

def finder(arr1,arr2):
   arr1.sort()
   arr2.sort()
   count = {}
   for x in arr1:
       if x in arr2:
           count[x] += 1
   print(count)
JNYRanger
  • 6,829
  • 12
  • 53
  • 81
Vish P
  • 1
  • 1
  • 6
    Welcome to Stack Overflow. [Please don't post screenshots of text](https://meta.stackoverflow.com/a/285557/354577). They can't be searched or copied, or even consumed by users of adaptive technologies like screen readers. Instead, paste the code as text directly into your question. If you select it and click the `{}` button or Ctrl+K the code block will be indented by four spaces, which will cause it to be rendered as code. – ChrisGPT was on strike Jul 28 '22 at 02:32
  • 1
    Welcome to Stack Overflow. Please read [ask], and show your code in the question itself, not as an image. Please also read [mre]. We [will not transcribe](https://meta.stackoverflow.com/questions/415040) the image for you. – Karl Knechtel Jul 28 '22 at 02:42
  • " I keep getting the above error but I can't make sense of it." What don't you understand about it? Did you try to read it? Do you know which part of the code it's talking about? Do you understand what kind of error it is? Do you think that part of the code should work anyway? If so, why? What do you think should happen, and why? – Karl Knechtel Jul 28 '22 at 02:43
  • 1
    (Hint: if I have an empty dictionary like `x = {}`, and then I try `x['test'] += 1`, what should the result be? Why? Think about it - what does `+=` mean? What starting value should I expect the `1` to be added to? Why? How?) – Karl Knechtel Jul 28 '22 at 02:44
  • Also, think carefully about *what the result should be*. Are you actually trying to **count** matches, or just figure out *which values* are present in both lists? Finally: sorting lists does not help `in` work any better, because the code for `in` has no way to know that the list is sorted - it still has to check every element. – Karl Knechtel Jul 28 '22 at 02:48
  • Does [Best way to handle a keyerror in a dict](https://stackoverflow.com/questions/36597869/best-way-to-handle-a-keyerror-in-a-dict) answer your question. – wwii Jul 28 '22 at 03:24

1 Answers1

0

This functionality is already implemented by the built-in set type

{1,2,3,4,5} & {1,2,3,4,5,6}

>>> {1, 2, 3, 4, 5}

Epik
  • 34
  • 2