-1

I have a question for my understanding of the below code. I understand the difference between a normal dict and a defaultdict, but my question is that with the below code, when I replace defaultdict with just dict() or {}, I get a KeyValue error for 7 (the first number in the list), why is this?

Surely it shouldn't return an error when called, because 7 is in the list?? Thanks

nums = [7,6,7,12]

class Solution:
    def singleNumber(self, nums):
        hash_table = defaultdict(int)      
                      
        for i in nums:
            hash_table[i] += 1       

        print(hash_table)

        for i in hash_table:
            if hash_table[i] == 1:         
                return i


x = Solution()
print(x.singleNumber(nums))
  • `hash_table[i] += 1` fails on dict if `i` is not in the dict. And there is noting in a new dict. – zvone Jan 10 '21 at 14:06
  • 1
    You can't increment something that's not there. Read more about how `collections.defaultdict` works [here](https://stackoverflow.com/questions/5900578/how-does-collections-defaultdict-work) – costaparas Jan 10 '21 at 14:08
  • 1
    Does this answer your question? [What is the difference between dict and collections.defaultdict?](https://stackoverflow.com/questions/6589814/what-is-the-difference-between-dict-and-collections-defaultdict) – costaparas Jan 10 '21 at 14:09
  • "Surely it shouldn't return an error when called, because 7 is in the list?" What does it being in the list have to do with the *dictionary key* error? A key error tells you it isn't *in the dict* which is true Can you explain what you think the difference is between a defaultdict and a regular dict, because *this case is the important difference* – juanpa.arrivillaga Jan 10 '21 at 14:22

1 Answers1

1

The number 7 is in your list nums, but it isn't automatically in the dictionary.

The line hash_table[i] += 1 looks up the value of i in hash_table, adds one to it, and then changes the value in the hash_table. But it can't look up the value of 7 in hash_table if hash_table is an ordinary dictionary, because 7 was never added to the dictionary.

With a defaultdict, the code works because when it tries to look up the value 7 in hash_table, it discovers that 7 is not in the hash_table yet, and so it returns the default value, which in this case is 0. It then adds 1 to that, and then changes the value in the dictionary.

Dylan
  • 226
  • 1
  • 4