r/pythonhelp • • Nov 18 '21

HOMEWORK Python exercise

Hello,

I've got the following question in my programming class, but have no idea how to solve this. (I know this is A easy question for you....) Could anyone kindly explain this with a solution ?

Fill in the gaps in the Python code, so that it returns the following output : [2, -5, 1, -3, 7]

d = {1: 2, 🔲: 4, -5:🔲, 2: 0, 🔲:🔲 }   
a = [0, 0, 0, 0, 0]  
    
for k in d:               
    v = d[k]              
    a[v] = k      

print(a)
0 Upvotes

2 comments sorted by

1

u/[deleted] Nov 18 '21

So the key of each entry in the dictionary d has a value which is used as an index position in the list a. So, the first key is 1 which has a value of 2 which says the int in the 3rd position in a, i.e. a[2] should be the same as the key, i.e. 1 and indeed the correct answers [2, -5, 1, -3, 7] shows that to be correct. You just need to work through.