Q. Find the error in the following code fragment. State the reason behind the error.
box = {}
jars = {}
crates = {}
box['biscuit'] = 1
box['cake' ] = 3
jars['jam'] = 4
crates['box'] = box
crates['jars'] = jars
print (crates [box])
Answer :-
The above code will produce error with print() because it is trying to print the value from dictionary crates by specify a key which is of a mutable type dictionary(box is a dictionary). There can never be a key of mutable type in a dictionary, hence the error.
The above code can be corrected by changing the print() as :
print (crates['box']).
Example :-
box = {} jars = {} crates = {} box['biscuit'] = 1 box['cake' ] = 3 jars['jam'] = 4 crates['box'] = box crates['jars'] = jars print (crates ['box'])
Output :-
{'biscuit': 1, 'cake': 3}
>>>
Post a Comment
You can help us by Clicking on ads. ^_^
Please do not send spam comment : )