mhawk
mhawk

Reputation: 27

Appending element to a dictionary python

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!

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:\Users\Larionova\Desktop\containsNearbyDuplicate.py", line 14, in s1 = Solution().containsNearbyDuplicate(list1, 3) File "C:\Users\Larionova\Desktop\containsNearbyDuplicate.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)

Upvotes: 0

Views: 68

Answers (2)

Vishesh Varma
Vishesh Varma

Reputation: 38

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.

Upvotes: 0

user16004728
user16004728

Reputation:

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

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

Upvotes: 3

Related Questions