Skip to content

Question 15

What is the output of the following code?

1
2
3
4
5
6
me = {'IT5001': {'marks': {'pe': 65, 'midterm': 72}, 'final': True}}
hack = me['IT5001']['marks'].copy()
hack['pe'] = 99
hack['final'] = None
me['IT5001']['marks'] = hack
print(me.get('IT5001'))
Hint

Notice the use of the copy() function when defining the value of hack. When you reassign hack['pe'] to be 99 and hack['final'] = None, does it change the contents of marks inside IT5001 inside me?

Solution

hack was initialized to contain a copy of me['IT5001']['marks']. In this instance, the value of hack is {'pe': 65, 'midterm': 72}. Because it was produced using the copy() method, changing the value of hack['pe'] to be 99 would not change that of me['IT5001']['marks']['pe']. In this context, hack was produced using a 1-layer deep copy, so the contents of hack will are not linked with that of me['IT5001']['marks']. At this moment,

me = {'IT5001': {'marks': {'pe': 65, 'midterm': 72}, 'final': True}}
hack = {'pe': 99, 'midterm': 72}

Now adding onto this, executing hack['final'] = None would not produce a same key-value pair in me['IT5001']['marks'], hence me['IT5001']['marks']['final'] does not exist.

me = {'IT5001': {'marks': {'pe': 65, 'midterm': 72}, 'final': True}}
hack = {'pe': 99, 'midterm': 72, 'final': None}

Now, run me['IT5001']['marks'] = hack. This would make me['IT5001']['marks'] now have its contents linked to the value of hack.

me = {'IT5001': {'marks': {'pe': 99, 'midterm': 72, 'final': None}, 'final': True}}
hack = {'pe': 99, 'midterm': 72, 'final': None}

By all accounts, once you realize this is an instance of shallow copying the value of hack here to replace the initial one, this would now mean all further changes to hack will propagate to me['IT5001']['marks']. Wow, talk about a breach of integrity here.

Answer
{'marks': {'pe': 99, 'midterm': 72, 'final': None}, 'final': True}