Appending element to a dictionary python

Question:

I was wondering what is the difference between this two code examples. The first one doesn’t work(Key error) but the second one works perfectly. I was using the append function and somehow it didn’t work for me. Can someone explain why is it. Thank you!

  • First one (with key error)
class Solution:
    def containsNearbyDuplicate(self, nums: List[int], k: int) -> bool:
        map = dict()
        for i, j in enumerate(nums):
            map[i].append(j) #adding the element using append function
        return(map)

Traceback (most recent call last):
File "C:UsersLarionovaDesktopcontainsNearbyDuplicate.py", line 14, in
s1 = Solution().containsNearbyDuplicate(list1, 3)
File "C:UsersLarionovaDesktopcontainsNearbyDuplicate.py", line 11, in containsNearbyDuplicate
map[i].append(j)
KeyError: 0

class Solution:
    def containsNearbyDuplicate(self, nums: List[int], k: int) -> bool:
        map = dict()
        for i, j in enumerate(nums):
            map[i] = j
        return(map)
Asked By: mhawk

||

Answers:

map[i].append(j) assumes that map[i] already holds a list.

map[i] = j just sets (or overrides) the value of map[i].

Answered By: bbbbbbbbb

The way that I remember the difference is:
In the first example, you’re using the dot operator, which is used to access the object’s data members and member functions. The first example is the same as:

temp = map[i]
temp.append(j)

dot operator works on temp, an existing object that holds the value map[i]. In your example, map is initially an empty dictionary. So, map[0] doesn’t exist because there’s no key 0. That is why you get the key error.

In the bottom example, you’re using an assignment operator, which copies the data from the RHS to the LHS. If the object on the left doesn’t exist, it makes one. So, in your case, map[0] doesn’t exist, but because of the assignment operator, you assign a value after creating an object map[0], thus adding a new key-value pair to the map dict.

Answered By: Vishesh Varma
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.