Dictionaries
Type B: Application Based Questions
1. Which of the following will result in an error for a given valid dictionary D?
(a) D+3
(b) D*3
(c) D + {3 : "3"}
(d) D.update( {3 : "3"})
(e) D.update { {"3" : 3}}
(f) D.update("3" : 3)
Ans. (a) D + 3 — This will result in an error as dictionary does not support + operation.
(b) D * 3 — This will result in an error as dictionary does not support * operation.
(c) D + {3 : "3"} — This will result in an error as dictionary does not support +
operation..
(d) D.update( {3 : "3"}) — This will execute with no error since valid dictionary is
passed to update( ) method.
(e) D.update { {"3" : 3}} — This will result in an error since update( ) method syntax
used here is invalid.
(f) D.update("3" : 3) — This will result in an error since update( ) method always
takes dictionary as it arguments which is not passed here. Hence it will lead to an
error.
2. The following code is giving some error. Find out the error and correct it.
d1 = {"a" : 1, 1 : "a", [1, "a"] : "two"}
Ans. This type of error occurs when a mutable type is used as a key in dictionary.
In d1, [1, "a"] is used as a key which is a mutable type of list. It will generate the below
error:
TypeError: unhashable type: 'list'
This error can be fixed by using a tuple as a key instead of list as shown below:
d1 = {"a" : 1, 1 : "a", (1, "a") : "two"}
3. The following code has two dictionaries with tuples as keys. While one of these
dictionaries being successfully created, the other is giving some error. Find out
which dictionary will be created successfully and which one will give error and
correct it:
dict1 = { (1, 2) : [1, 2], (3, 4) : [3, 4]}
dict2 = { ([1], [2]) : [1,2], ([3], [4]) : [3, 4]}
Ans. dict1 will be created successfully because tuples are used as keys. As tuples are
immutable, therefore it won't give any error.
dict2 will give an error because the tuples used as keys of dict2 contain lists as their
elements. As lists are mutable, so they can't appear in keys of the dictionary.
It can be corrected by removing list elements from the tuples as shown below:
dict2 = { (1,2) : [1,2], (3,4) : [3, 4]}
4. Nesting of dictionary allows you to store a dictionary inside another dictionary.
Then why is following code raising error? What can you do to correct it?
d1 = {1 : 10, 2 : 20, 3 : 30}
d2 = {1 : 40, 2 : 50, 3 : 60}
d3 = {1 : 70, 2 : 80, 3 : 90}
d4 = {d1 : "a", d2 : "b", d3 : "c"}
Ans. Dictionaries can be stored inside another dictionary as values and not as keys. Here, d4
is storing the other dictionaries as keys which is not allowed because dictionaries are
mutable objects. That's why this code is raising error.
It can be corrected by using d1, d2, d3 as values of d4.
The corrected code is shown below:
d4 = { "a": d1, "b": d2, "c": d3}
5. Find the output of the following code snippet.
dic1 = {'age': 25, 'name': 'xyz', 'salary': 23450.5}
val = dic1['age']
if val in dic1:
print("This is member of the dictionary")
else :
print("This is not a member of the dictionary")
Ans. This is not a member of the dictionary
6. What is the output produced by the following code:
d1 = {5 : [6, 7, 8], "a" : (1, 2, 3)}
print(d1.keys())
print(d1.values())
Ans. dict_keys([5, 'a'])
dict_values([[6, 7, 8], (1, 2, 3)])
7. Consider the following code and then answer the questions that follow:
myDict = {'a' : 27, 'b' : 43, 'c' : 25, 'd' : 30}
valA =''
for i in myDict :
if i > valA :
valA = i
valB = myDict[i]
print(valA) #Line1
print(valB) #Line2
print(30 in myDict) #Line3
myLst = list(myDict.items())
myLst.sort() #Line4
print(myLst[-1]) #Line5
(a) What output does Line 1 produce?
(b) What output does Line 2 produce?
(c) What output does Line 3 produce?
(d) What output does Line 5 produce?
(e) What is the return value from the list sort( ) function (Line 4)?
Ans. (a) 'd'
(b) 30
(c) False
(d) ('d',30)
(e) sort() function of list doesn’t return anything. So it returns None by default.
8. What will be the output produced by following code?
d1 = { 5 : "number", "a" : "string", (1, 2): "tuple" }
print("Dictionary contents")
for x in d1.keys(): # Iterate on a key list
print (x, ':' , d1[x], end = ' ')
print (d1[x] * 3)
print ( )
Ans. Dictionary contents
5 : number numbernumbernumber
a : string stringstringstring
(1, 2) : tuple tupletupletuple
9. Predict the output:
(a) d = dict()
d['left'] = '<'
d['right'] = '>'
print('{left} and {right} or {right} and {left}')
Ans. {left} and {right} or {right} and {left}
(b) text = "abracadabraaabbccrr"
counts = {}
ct = 0
lst = []
for word in text:
if word not in lst:
lst.append(word)
counts[word] = 0
ct = ct + 1
counts[word] = counts[word] + 1
print(counts)
print(lst)
Ans. {'a': 7, 'b': 4, 'r': 4, 'c': 3, 'd': 1}
['a', 'b', 'r', 'c', 'd']
(c) list1 = [2, 3, 3, 2, 5,3, 2, 5, 1,1]
counts = {}
ct = 0
lst = []
for num in list1:
if num not in lst:
lst.append(num)
counts[num] = 0
ct = ct+1
counts[num] = counts[num]+1
print(counts)
for key in counts.keys():
counts[key] = key * counts[key]
print(counts)
Ans. {2: 3, 3: 3, 5: 2, 1: 2}
{2: 6, 3: 9, 5: 10, 1: 2}
11. Find the errors.
(a) text = "abracadbra"
counts = {}
for word in text :
counts[word] = counts[word] + 1
Ans. KeyError: 'a'
(b) my_dict = {}
my_dict[(1,2,4)] = 8
my_dict[[4,2,1]] = 10
print(my_dict)
Ans. TypeError: unhashable type: 'list'
12. Predict the output:
(a) fruit = {}
L1 = ['Apple', 'banana', 'apple']
for index in L1 :
if index in fruit:
fruit[index] += 1
else :
fruit[index] = 1
print(len(fruit))
print(fruit)
Ans. 3
{'Apple': 1, 'banana': 1, 'apple': 1}
(b) arr = {}
arr[1] = 1
arr['1'] = 2
arr[1] += 1
sum = 0
for k in arr:
sum += arr[k]
print(sum)
Ans. 4
13. Predict the output
(a) a = {(1,2):1,(2,3):2}
print(a[1,2])
Ans. 1
(b) a = {'a':1, 'b':2, 'c':3}
print(a['a','b'])
Ans. KeyError: ('a', 'b')
14. 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']))
Ans. The code given in set (a) will produce an error. In line 5.
The code given in set (b) is correct. Its output is as shown below:
Output of set (b) code
2
15. 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)
Ans. 1 0
14
6