Computer Science

Find the error/output. Consider below given two sets of codes. Which one will produce an error? Also, predict the output produced by the correct code.

(a)

box = {}
jars = {'Jam' :4}
crates = {}	
box['biscuit'] = 1	
box['cake'] = 3	
crates['box'] = box	
crates['jars'] = jars	
print(len(crates[box]))

(b)

box = {}
jars = {'Jam' :4}
crates = {}	
box['biscuit'] = 1	
box['cake'] = 3	
crates['box'] = box	
crates['jars'] = jars	
print(len(crates['box']))

Python Dictionaries

9 Likes

Answer

The code given in set (a) will produce an error.
In the line print(len(crates[box])), we are trying to print the value from dictionary crates by taking mutable type dictionary i.e box as key — crates[box]. The keys of the dictionary cannot be of mutable type, hence this code produces this error.

The code given in set (b) is correct. Its output is as shown below:

Output of set (b) code
2
Explanation

crates['box'] will return the value of key 'box' from dictionary crates i.e, box. box is itself a dictionary containing two key-value pairs i.e:
{'biscuit': 1, 'cake': 3}
Therefore, the expression len(crates['box']) becomes len(box) which will return the length of box i.e., 2.

Answered By

4 Likes


Related Questions