Math142
Math142

Reputation: 19

I try to add a list at a specific key but list empty in dictionary

for student_id in range(1,len(student)+1):
    for test_id in range(len(marks)):
        if marks["student_id"][test_id] == student_id:
            test_list.append(marks["test_id"][test_id])
    
    test_dict[student_id] = [test_list]
    test_list.clear()

print(test_dict)

I made some test and the list contents some result before adding the list to the dictionary but in the dictionary it is empty. When I searched on the internet, everything looks normal.

Upvotes: 0

Views: 37

Answers (1)

fsimonjetz
fsimonjetz

Reputation: 5802

The more pythonic way would be something like this:

for student_id in range(1,len(student)+1):
    
    # make a new list for every iteration
    test_list = []
    
    for test_id in range(len(marks)):
        if marks["student_id"][test_id] == student_id:
            test_list.append(marks["test_id"][test_id])
    
    test_dict[student_id] = test_list # no additional []
    # no .clear()

print(test_dict)

Upvotes: 1

Related Questions