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
Predict the output
a = {(1,2):1,(2,3):2} print(a[1,2])Predict the output
a = {'a':1, 'b':2, 'c':3} print(a['a','b'])Predict the output :
dct = {} dct[1] = 1 dct ['1'] = 2 dct[1.0] = 4 sum = 0 for k in dct: print(k, sum) sum += dct[k] print(sum)Fill in the blanks of the following code so that the values and keys of dictionary d are inverted to create dictionary fd.
d = {'a':1, 'b':2, 'c':3} print(d) fd = {} for key, value in d.____(): fd[____] = ____ print(fd)