Dictionary:Get(): AttributeError: 'NoneType' object has no attribute 'append'

Question:

Here i am trying to append in a dict. if key exist or else create a new list and then append.
Using get() function.

But its giving error of ‘NONE Type objects.

class Solution:

    def solve(self, A, B):
        save_x={}
        save_y={}
        l=len(A)
        for i in range(l):
            save_x[A[i]]=save_x.get(A[i],[]).append(B[i])
            save_y[B[i]]=save_y.get(B[i],[]).append(A[i])

        print(save_x,save_y)
Asked By: deepak dash

||

Answers:

list.append doesn’t return something (returns None), you can fix your issue changing the for loop with:

for i in range(l):
    save_x[A[i]] = save_x.get(A[i], []) + [B[i]]
    save_y[B[i]] = save_y.get(B[i], []) + [A[i]]

this version is a bit slow since it is creating a new list at each iteration

or you could use dict.setdefault and update a key if already exists (a bit faster):

for i in range(l):
    save_x.setdefault(A[i], []).append(B[i])
    save_y.setdefault(B[i], []).append(A[i])

the best option will be to use collections.defaultdict:

from collections import defaultdict


save_x = defaultdict(list)
save_y = defaultdict(list)
for a, b in zip(A, B):
    save_x[a].append(b)
    save_y[b].append(a)
Answered By: kederrac
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.