0

Need to check I'm understanding this right. I'm running a function that appends lists to a list in a nested dictionary. I thought I would be able to assign a variable to append and return the same values as the nested dictionary, but it returns 'None', (and interestingly still appends the nested dictionary even though it's in an append function that returns None?)... so is the best way of returning the nested values by using multiple/nested .get() functions as below?

scores = {"class1": {'nest1':{'nest2':[]}}} 
get_nested_list = []
test_var = []

def main():
    for i in range(0,3):
        test_var.append(scores["class1"]['nest1']['nest2'].append([i,i+1,i+2]))
    
main()

get_nested_list = scores.get("class1").get('nest1').get('nest2')

print(test_var)
print(get_nested_list)

Output...

[None, None, None]
[[0,1,2],[1,2,3],[2,3,4]]
Pranav Hosangadi
  • 23,755
  • 7
  • 44
  • 70
Dan
  • 229
  • 2
  • 6

2 Answers2

2

If you know that scores['class1']['nest1']['nest2'] exists, there is no difference between that and a chain of .get()s.

You're correct in thinking that the return value of append is None. If you want to append the newly updated list under scores['class1']['nest1']['nest2'], you'll be better off splitting up your iteration into two lines:

for i in range(0, 3):
    scores['class1']['nest1']['nest2'].append([i, i+1, i+2])
    test_var.append(scores['class1']['nest1']['nest2'])
aybry
  • 316
  • 1
  • 7
0

The list append method doesn't return anything (or return None to say), this is why your loop inside the main function keeps appending None to test_var. The append function returns nothing doesn't mean that it's not performing any operation. It certainly adds a new list item to the list in the dictionary scores.

Also, you may simply use

scores["class1"]['nest1']['nest2']

instead of the get method to access the list in nested dictionary

Abhistar
  • 85
  • 9