Test Series - python

Test Number 58/108

Q: Which of the following isn’t true about dictionary keys?
A. More than one key isn’t allowed
B. Keys must be immutable
C. Keys must be integers
D. When duplicate keys encountered, the last assignment wins
Solution: Keys of a dictionary may be any data type that is immutable.
Q: What will be the output of the following Python code?

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}
Solution: pop() method removes the key-value pair for the key mentioned in the pop() method.
Q: What will be the output of the following Python code?

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
Solution: 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.
Q: What will be the output of the following Python code?

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():
Solution: The variable i iterates over the keys of the dictionary and hence the keys are printed.
Q: What will be the output of the following Python code?

>>> 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’)])
Solution: The method items() returns list of tuples with each tuple having a key-value pair.
Q: Which of the statements about dictionary values if false?
A. More than one key can have the same value
B. The values of the dictionary can be accessed as dict[key]
C. Values of a dictionary must be unique
D. Values of a dictionary can be a mixture of letters and numbers
Solution: More than one key can have the same value.
Q: What will be the output of the following Python code snippet?

>>> 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
Solution: del deletes the entire dictionary and any further attempt to access it will throw an error.
Q: If a is a dictionary with some key-value pairs, what does a.popitem() do?
A. Removes an arbitrary element
B. Removes all the key-value pairs
C. Removes the key-value pair for the key given as an argument
D. Invalid method for dictionary
Solution: The method popitem() removes a random key-value pair.

You Have Score    /8