Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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!

  • 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:\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)

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading