Python Questions and Answers - Dictionary - 1: "John" "Peter"
Python Questions and Answers - Dictionary - 1: "John" "Peter"
Python Questions and Answers - Dictionary - 1: "John" "Peter"
This set of Python Multiple Choice Questions & Answers (MCQs) focuses on
“Dictionaries”.
Answer: d
Explanation: Dictionaries are created by specifying keys and values.
Answer: b
Explanation: Dictionaries appear in the form of keys and values.
advertisement
a) True
b) False
c) None
d) Error
Answer: a
Explanation: In can be used to check if the key is int dictionary.
a) True
b) False
c) None
d) Error
Answer: b
Explanation: If d2 was initialized as d2 = d1 the answer would be true.
a) True
b) False
c) Error
d) None
Answer: c
Explanation: Arithmetic > operator cannot be used with dictionaries.
a) 40
b) 45
c) “john”
d) “peter”
Answer: a
Explanation: Execute in the shell to verify.
7. Suppose d = {“john”:40, “peter”:45}, to delete the entry for “john” what command do
we use?
a) d.delete(“john”:40)
b) d.delete(“john”)
c) del d[“john”]
d) del d(“john”:40)
Answer: c
Explanation: Execute in the shell to verify.
Answer: b
Explanation: Execute in the shell to verify.
Answer: a
Explanation: The output of the code shown above is a list containing only keys of the
dictionary d, in the form of a list.
10. Suppose d = {“john”:40, “peter”:45}, what happens when we try to retrieve a value
using the expression d[“susan”]?
a) Since “susan” is not a value in the set, Python raises a KeyError exception
b) It is executed fine and no exception is raised, and it returns None
c) Since “susan” is not a key in the set, Python raises a KeyError exception
d) Since “susan” is not a key in the set, Python raises a syntax error
Answer: c
Explanation: Execute in the shell to verify.
This set of Python Multiple Choice Questions & Answers (MCQs) focuses on “Dictionary
– 2”.
Answer: b
Explanation: The values of a dictionary can be accessed using keys but the keys of a
dictionary can’t be accessed using values.
Answer: c
Explanation: Option c is a set, not a dictionary.
advertisement
a={1:"A",2:"B",3:"C"}
for i,j in a.items():
print(i,j,end=" ")
a) 1 A 2 B 3 C
b) 1 2 3
c) A B C
d) 1:”A” 2:”B” 3:”C”
Answer: a
Explanation: In the above code, variables i and j iterate over the keys and values of the
dictionary respectively.
a={1:"A",2:"B",3:"C"}
print(a.get(1,4))
a) 1
b) A
c) 4
d) Invalid syntax for get method
Answer: b
Explanation: The get() method returns the value of the key if the key is present in the
dictionary and the default value(second parameter) if the key isn’t present in the
dictionary.
a={1:"A",2:"B",3:"C"}
print(a.get(5,4))
a) Error, invalid syntax
b) A
c) 5
d) 4
Answer: d
Explanation: The get() method returns the default value(second parameter) if the key
isn’t present in the dictionary.
a={1:"A",2:"B",3:"C"}
print(a.setdefault(3))
a) {1: ‘A’, 2: ‘B’, 3: ‘C’}
b) C
c) {1: 3, 2: 3, 3: 3}
d) No method called setdefault() exists for dictionary
Answer: b
Explanation: setdefault() is similar to get() but will set dict[key]=default if key is not
already in the dictionary.
7. What will be the output of the following Python code snippet?
a={1:"A",2:"B",3:"C"}
a.setdefault(4,"D")
print(a)
a) {1: ‘A’, 2: ‘B’, 3: ‘C’, 4: ‘D’}
b) None
c) Error
d) [1,3,6,10]
Answer: a
Explanation: setdefault() will set dict[key]=default if key is not already in the dictionary.
a={1:"A",2:"B",3:"C"}
b={4:"D",5:"E"}
a.update(b)
print(a)
a) {1: ‘A’, 2: ‘B’, 3: ‘C’}
b) Method update() doesn’t exist for dictionaries
c) {1: ‘A’, 2: ‘B’, 3: ‘C’, 4: ‘D’, 5: ‘E’}
d) {4: ‘D’, 5: ‘E’}
Answer: c
Explanation: update() method adds dictionary b’s key-value pairs to dictionary a.
Execute in python shell to verify.
a={1:"A",2:"B",3:"C"}
b=a.copy()
b[2]="D"
print(a)
a) Error, copy() method doesn’t exist for dictionaries
b) {1: ‘A’, 2: ‘B’, 3: ‘C’}
c) {1: ‘A’, 2: ‘D’, 3: ‘C’}
d) “None” is printed
Answer: b
Explanation: Changes made in the copy of the dictionary isn’t reflected in the original
one.
a={1:"A",2:"B",3:"C"}
a.clear()
print(a)
a) None
b) { None:None, None:None, None:None}
c) {1:None, 2:None, 3:None}
d) { }
Answer: d
Explanation: The clear() method clears all the key-value pairs in the dictionary.
Answer: c
Explanation: Keys of a dictionary may be any data type that is immutable.
a={1:5,2:3,3:4}
a.pop(3)
print(a)
a) {1: 5}
b) {1: 5, 2: 3}
c) Error, syntax error for pop() method
d) {1: 5, 3: 4}
Answer: b
Explanation: pop() method removes the key-value pair for the key mentioned in the pop()
method.
a={1:5,2:3,3:4}
print(a.pop(4,9))
a) 9
b) 3
c) Too many arguments for pop() method
d) 4
Answer: a
Explanation: pop() method returns the value when the key is passed as an argument
and otherwise returns the default value(second argument) if the key isn’t present in the
dictionary.
a={1:"A",2:"B",3:"C"}
for i in a:
print(i,end=" ")
a) 1 2 3
b) ‘A’ ‘B’ ‘C’
c) 1 ‘A’ 2 ‘B’ 3 ‘C’
d) Error, it should be: for i in a.items():
Answer: a
Explanation: The variable i iterates over the keys of the dictionary and hence the keys
are printed.
>>> a={1:"A",2:"B",3:"C"}
>>> a.items()
a) Syntax error
b) dict_items([(‘A’), (‘B’), (‘C’)])
c) dict_items([(1,2,3)])
d) dict_items([(1, ‘A’), (2, ‘B’), (3, ‘C’)])
Answer: d
Explanation: The method items() returns list of tuples with each tuple having a key-value
pair.
This set of Python Multiple Choice Questions & Answers (MCQs) focuses on “Dictionary
– 3”.
Answer: c
Explanation: More than one key can have the same value.
>>> a={1:"A",2:"B",3:"C"}
>>> del a
a) method del doesn’t exist for the dictionary
b) del deletes the values in the dictionary
c) del deletes the entire dictionary
d) del deletes the keys in the dictionary
Answer: c
Explanation: del deletes the entire dictionary and any further attempt to access it will
throw an error.
advertisement
Answer: a
Explanation: The method popitem() removes a random key-value pair.
total={}
def insert(items):
if items in total:
total[items] += 1
else:
total[items] = 1
insert('Apple')
insert('Ball')
insert('Apple')
print (len(total))
a) 3
b) 1
c) 2
d) 0
Answer: c
Explanation: The insert() function counts the number of occurrences of the item being
inserted into the dictionary. There are only 2 keys present since the key ‘Apple’ is
repeated. Thus, the length of the dictionary is 2.
a = {}
a[1] = 1
a['1'] = 2
a[1]=a[1]+1
count = 0
for i in a:
count += a[i]
print(count)
a) 1
b) 2
c) 4
d) Error, the keys can’t be a mixture of letters and numbers
Answer: c
Explanation: The above piece of code basically finds the sum of the values of keys.
numbers = {}
letters = {}
comb = {}
numbers[1] = 56
numbers[3] = 7
letters[4] = 'B'
comb['Numbers'] = numbers
comb['Letters'] = letters
print(comb)
a) Error, dictionary in a dictionary can’t exist
b) ‘Numbers’: {1: 56, 3: 7}
c) {‘Numbers’: {1: 56}, ‘Letters’: {4: ‘B’}}
d) {‘Numbers’: {1: 56, 3: 7}, ‘Letters’: {4: ‘B’}}
Answer: d
Explanation: Dictionary in a dictionary can exist.
Answer: a
Explanation: In the second line of code, the dictionary becomes an empty dictionary.
Thus, length=0.
Answer: b
Explanation: After the key-value pair of 1:’A’ is deleted, the key-value pair of 1:’D’ is
added.
a = {}
a[1] = 1
a['1'] = 2
a[1.0]=4
count = 0
for i in a:
count += a[i]
print(count)
a) An exception is thrown
b) 3
c) 6
d) 2
Answer: c
Explanation: The value of key 1 is 4 since 1 and 1.0 are the same. Then, the function
count() gives the sum of all the values of the keys (2+4).
10. What will be the output of the following Python code snippet?
a={}
a['a']=1
a['b']=[2,3,4]
print(a)
a) Exception is thrown
b) {‘b’: [2], ‘a’: 1}
c) {‘b’: [2], ‘a’: [3]}
d) {‘b’: [2, 3, 4], ‘a’: 1}
Answer: d
Explanation: Mutable members can be used as the values of the dictionary but they
cannot be used as the keys of the dictionary.
11. What will be the output of the following Python code snippet?
>>>import collections
>>> a=collections.Counter([1,1,2,3,3,4,4,4])
>>> a
a) {1,2,3,4}
b) Counter({4, 1, 3, 2})
c) Counter({4: 3, 1: 2, 3: 2, 2: 1})
d) {4: 3, 1: 2, 3: 2, 2: 1}
Answer: c
Explanation: The statement a=collections.OrderedDict() generates a dictionary with the
number as the key and the count of times the number appears as the value.
12. What will be the output of the following Python code snippet?
>>>import collections
>>> b=collections.Counter([2,2,3,4,4,4])
>>> b.most_common(1)
a) Counter({4: 3, 2: 2, 3: 1})
b) {3:1}
c) {4:3}
d) [(4, 3)]
Answer: d
Explanation: The most_common() method returns the n number key-value pairs where
the value is the most recurring.
13. What will be the output of the following Python code snippet?
>>>import collections
>>> b=collections.Counter([2,2,3,4,4,4])
>>> b.most_common(1)
a) Counter({4: 3, 2: 2, 3: 1})
b) {3:1}
c) {4:3}
d) [(4, 3)]
Answer: d
Explanation: The most_common() method returns the n number key-value pairs where
the value is the most recurring.
14. What will be the output of the following Python code snippet?
Answer: a
Explanation: a|b returns the pair of keys and the highest recurring value.
15. What will be the output of the following Python code snippet?
Answer: b
Explanation: a&b returns the pair of keys and the lowest recurring value.
class demo(dict):
def __test__(self,key):
return []
a = demo()
a['test'] = 7
print(a)
a) True
b) False
Answer: b
Explanation: The output of the code is: {‘test’:7}.
count={}
count[(1,2,4)] = 5
count[(4,2,1)] = 7
count[(1,2)] = 6
count[(4,2,1)] = 2
tot = 0
for i in count:
tot=tot+count[i]
print(len(count)+tot)
a) 25
b) 17
c) 16
d) Tuples can’t be made keys of a dictionary
Answer: c
Explanation: Tuples can be made keys of a dictionary. Length of the dictionary is 3 as
the value of the key (4,2,1) is modified to 2. The value of the variable tot is 5+6+2=13.
a={}
a[2]=1
a[1]=[2,3,4]
print(a[1][1])
a) [2,3,4]
b) 3
c) 2
d) An exception is thrown
Answer: b
Explanation: Now, a={1:[2,3,4],2:1} . a[1][1] refers to second element having key 1.
Answer: a
Explanation: Return a new sorted list of keys in the dictionary.
Answer: d
Explanation: Dictionary comprehension is implemented in the above piece of code.
>>> a={}
>>> a.fromkeys([1,2,3],"check")
a) Syntax error
b) {1:”check”,2:”check”,3:”check”}
c) “check”
d) {1:None,2:None,3:None}
Answer: b
Explanation: The dictionary takes values of keys from the list and initializes it to the
default value (value given in the second parameter). Execute in Python shell to verify.
>>> b={}
>>> all(b)
a) { }
b) False
c) True
d) An exception is thrown
Answer: c
Explanation: Function all() returns True if all keys of the dictionary are true or if the
dictionary is empty.
Answer: a
Explanation: Method any() returns True if any key of the dictionary is true and False if
the dictionary is empty.
>>> a={"a":1,"b":2,"c":3}
>>> b=dict(zip(a.values(),a.keys()))
>>> b
a) {‘a’: 1, ‘b’: 2, ‘c’: 3}
b) An exception is thrown
c) {‘a’: ‘b’: ‘c’: }
d) {1: ‘a’, 2: ‘b’, 3: ‘c’}
Answer: d
Explanation: The above piece of code inverts the key-value pairs in the dictionary.
Answer: b
Explanation: Dictionary comprehension and string concatenation is implemented in the
above piece of code.
>>> a=dict()
>>> a[1]
a) An exception is thrown since the dictionary is empty
b) ‘ ‘
c) 1
d) 0
Answer: a
Explanation: The values of a dictionary can be accessed through the keys only if the
keys exist in the dictionary.
Answer: b
Explanation: The statement a=collections.defaultdict(int) gives the default value of 0
(since int data type is given within the parenthesis) even if the keys don’t exist in the
dictionary.
Answer: b
Explanation: The statement a=collections.defaultdict(str) gives the default value of ‘ ‘
even if the keys don’t exist in the dictionary.
Answer: d
Explanation: The statement a=collections.defaultdict(lambda: x) gives the default value
of x even if the keys don’t exist in the dictionary.
Answer: b
Explanation: The line of code a=collections.OrderedDict() generates a dictionary
satisfying the conditions given within the parenthesis and in an ascending order of the
keys.