user3476463
user3476463

Reputation: 4575

update dict using nested for loop

I have the double for loop below. In the first for loop I'm iterating through the elements in tstLst1 and for each element I'm then iterating through the elements in tstLst2, testing each element to see if it's greater then 5, then appending the elements from tstLst2 in a new list tstEmpt1. I then update dict with the list of values from tstLst2 for each element of tstLst1 as keys. I'm getting the "Nonetype" error below, I'm not sure why. Can someone please point out the issue and suggest a solution?

Code:

tstLst1=[1,2,3]
tstLst2=[2,5,6]

tstDict1={}



for j in tstLst1:

    tstEmpt1=[]

    for i in tstLst2:

        if i >5:

            tstEmpt1=tstEmpt1.append(i)

    tstDict1=tstDict1.update({j:tstEmpt1})

error:

---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-19-89e025227797> in <module>
     16             tstEmpt1=tstEmpt1.append(i)
     17 
---> 18     tstDict1=tstDict1.update({j:tstEmpt1})
     19 

AttributeError: 'NoneType' object has no attribute 'update'

Upvotes: 2

Views: 1228

Answers (1)

Karel Tamayo
Karel Tamayo

Reputation: 3750

Your issue is that list.append() returns None so when you do tstEmpt1=tstEmpt1.append(i) you're appending the element and assigning None to the list. Next iteration throws because None has no attribute 'update' as the error states.

Same case with the dictionary.update().

Removing the assignments should do the trick for you:

for j in tstLst1:
  tstEmpt1=[]
  for i in tstLst2:
    if i >5:
      tstEmpt1.append(i)
  tstDict1.update({j:tstEmpt1})

Upvotes: 3

Related Questions