Home > Mobile >  Key error while adding a new key to the dictionary
Key error while adding a new key to the dictionary

Time:07-19

This is my code:

nums = sorted(nums)
n = len(nums)
maps = { 0 : [nums[0]]}
maps[2] = ["shot"]
dp = [1 for _ in nums]

for i in range(1 , n):
    for j in range(i , -1 , -1):
        if nums[i] % nums[j] == 0:
            dp[i] = dp[j] 1
            print(maps)
            if i not in maps.keys():
                maps[i] = maps[j].append(nums[i])

The error message:

    KeyError: 1
    maps[i] = maps[j].append(nums[i])
    Line 15 in largestDivisibleSubset (Solution.py)
    ret = Solution().largestDivisibleSubset(param_1)
    Line 41 in _driver (Solution.py)
    _driver()
    Line 52 in <module> (Solution.py)

The input: nums = [1,2,3,5,7]

CodePudding user response:

You can only use the append method to insert a value to a key, that is already existing. So either you do something like this:

maps[i] = nums[i]

Or:

maps[i] = nums[j]

CodePudding user response:

This is your problem stanza:

if i not in maps.keys():
  maps[i] = maps[j].append(nums[i])

Here you are asking 'if i is not in the maps dictionary, then get the value at index i from the nums array and append it to the value referenced by the key j in the maps dictionary, then assign the result of that function back to the value of the key i in the dictionary'.

append() returns None, which means you'll just be putting None at the key i. But your error is actually saying that the key 1 doesn't exist in the object you're looking into. Presumably that is maps, because you are attempting to dereference maps[j] - and j is not one of the keys in maps. Since that can't be fetched, and would be None if you did, you can't append anything to it.

A definitive solution can't be given here, since it's unclear what you want to end up with. Given an input array of [1,2,3,5,7] what do you expect maps to look like at the end of this function?

One thing that might help is something like:

if i not in maps.keys():
    ls = maps.get(j, [])
    ls.append(nums[i])
    maps[i] = ls

Here, we get the list at index j and return a default empty list [] if j is not inside the map already. Then we assign the modified list to the key i. I'm not sure if this is actually what you're looking for, though.

  • Related