Python Dictionary MCQ : Set 4

Python Dictionary MCQ

1). What is the output of the following code?

dict1 = {“m1”: 40, “m2”: 50, “m3”: None}
dict2 = {}
for key, val in dict1.items():
    if val != None:
        dict2[key] = val

print(dict2)

a) {“m1”: 40, “m2”: 50}
b) {“m1”: 40, “m2”: 50, “m3”: None}
c) {“m3”: None}
d) {}

Corresct answer is: a) {“m1”: 40, “m2”: 50}
Explanation: The code iterates over the key-value pairs in `dict1` using the `items()` method. It checks if the value is not equal to None and adds the key-value pair to `dict2`. In this case, the value of “m3” is None, so it is excluded from `dict2`. The output will be `{“m1”: 40, “m2”: 50}`, which are the key-value pairs that have a non-None value in `dict1`.

2). What is the output of the following code?

dict1 = {‘alex’: 50, ‘john’: 45, ‘Robert’: 30}
dict2 = {}

for key, val in dict1.items():
    if val > 40:
        dict2[key] = val
print(dict2)

a) {‘alex’: 50, ‘john’: 45}
b) {‘alex’: 50}
c) {‘john’: 45}
d) {}

Corresct answer is: a) {‘alex’: 50, ‘john’: 45}
Explanation: The code iterates over the key-value pairs in dict1 using the items() method. It checks if the value is greater than 40. If the condition is true, it adds the key-value pair to dict2. In this case, both ‘alex’ and ‘john’ have values greater than 40, so they are added to dict2. Therefore, the output is {‘alex’: 50, ‘john’: 45}.

3). What is the output of the following code?

dict1 = {‘name’:[‘Apr’,’May’,’June’],’month’:[4, 5, 6]}
res = dict(zip(dict1[‘name’],dict1[‘month’]))
print(res)

a) {‘Apr’: 4, ‘May’: 5, ‘June’: 6}
b) {‘name’: [‘Apr’, ‘May’, ‘June’], ‘month’: [4, 5, 6]}
c) {‘name’: ‘June’, ‘month’: 6}
d) {‘Apr’: [4, 5, 6], ‘May’: [4, 5, 6], ‘June’: [4, 5, 6]}

Corresct answer is: a) {‘Apr’: 4, ‘May’: 5, ‘June’: 6}
Explanation: The code uses the `zip()` function to combine the elements from `dict1[‘name’]` and `dict1[‘month’]` into pairs. The `dict()` function is then used to convert the resulting pairs into a dictionary. The output will be `{‘Apr’: 4, ‘May’: 5, ‘June’: 6}`, where the names are the keys and the corresponding months are the values.

4). What is the output of the following code?

list1 = [(“mike”,1),(“sarah”,20),(“jim”, 16)]
dict1 = {}
for val in list1:
    dict1[val[0]] = val[1]
print(dict1)

a) {‘mike’: 1, ‘sarah’: 20, ‘jim’: 16}
b) {‘mike’: 1, ‘sarah’: 20, ‘jim’: 16, ‘val’: 1, ‘val’: 20, ‘val’: 16}
c) {‘mike’: 1, ‘sarah’: 20, ‘jim’: 16, 0: ‘mike’, 1: ‘sarah’, 2: ‘jim’}
d) Error

Corresct answer is: a) {‘mike’: 1, ‘sarah’: 20, ‘jim’: 16}
Explanation: The code iterates over the list of tuples `list1` and assigns each tuple’s first element as a key and the second element as its corresponding value in the dictionary `dict1`. The resulting dictionary will contain the key-value pairs: {‘mike’: 1, ‘sarah’: 20, ‘jim’: 16}.

5). What is the output of the following code?

str1 = “Apr=April; Mar=March”
dictionary = dict(subString.split(“=”) for subString in str1.split(“;”))
print(dictionary)

a) {‘Apr’: ‘April’, ‘ Mar’: ‘March’}
b) {‘Apr’: ‘April’, ‘Mar’: ‘March’}
c) {‘Apr=April’: ‘Mar=March’}
d) Error

Corresct answer is: b) {‘Apr’: ‘April’, ‘Mar’: ‘March’}
Explanation: The code snippet splits the string `str1` into substrings using the “;” delimiter. It then splits each substring using the “=” delimiter to obtain key-value pairs. These key-value pairs are used to create a dictionary using the `dict()` constructor. The resulting dictionary will have keys ‘Apr’ and ‘Mar’ with corresponding values ‘April’ and ‘March’, respectively. The whitespaces before ‘Mar’ in option (a) are incorrect, and option (c) combines the entire input string as a single key. 

6). What is the output of the following code?

matrix = [[1,2,3],[4,5,6]]
dict1 = {}
for i in range(len(matrix)):
    dict1[i+1] = matrix[i]
print(dict1)

a) {1: [1,2,3], 2: [4,5,6]}
b) {0: [1,2,3], 1: [4,5,6]}
c) {1: [0,1,2], 2: [3,4,5]}
d) {0: [0,1,2], 1: [3,4,5]}

Corresct answer is: a) {1: [1,2,3], 2: [4,5,6]}
Explanation: The code initializes an empty dictionary `dict1` and then iterates over the indices of the `matrix`. For each index `i`, it assigns the value of `matrix[i]` to `dict1[i+1]`. Since the indices start from 0, `i+1` is used to create keys starting from 1. Therefore, the resulting dictionary is `{1: [1,2,3], 2: [4,5,6]}`.

7). What is the output of the following code?

D1 = {‘virat’: 50, ‘rohit’: 50, ‘rahul’: 50, ‘hardik’: 50}
result = all(x == 50 for x in D1.values())
print(result)

a) True
b) False
c) Error
d) None

Corresct answer is: a) True
Explanation: The code initializes a dictionary `D1` with keys `’virat’`, `’rohit’`, `’rahul’`, and `’hardik’`, each having a value of `50`. The expression `all(x == 50 for x in D1.values())` checks if all the values in the dictionary `D1` are equal to `50`. In this case, all the values in `D1` are indeed `50`, so the expression evaluates to `True`.

8). What is the output of the following code?

D1 = [(‘virat’,50), (‘rohit’,40), (‘virat’,30), (‘rohit’,10)]

def grouping_dictionary(l):
    result = {}
    for k, v in l:
        result.setdefault(k, []).append(v)
    return result

print(grouping_dictionary(D1))

a) {‘virat’: [50, 30], ‘rohit’: [40, 10]}
b) {‘virat’: [50, 30], ‘rohit’: [40]}
c) {‘virat’: [50], ‘rohit’: [40, 10]}
d) {‘virat’: [50], ‘rohit’: [40]}

Corresct answer is: a) {‘virat’: [50, 30], ‘rohit’: [40, 10]}
Explanation: The code defines a function `grouping_dictionary()` that takes a list of tuples as input. It iterates over each tuple and uses the `setdefault()` method to create a new key in the `result` dictionary if it doesn’t already exist, and appends the corresponding value to the list associated with that key. In this case, the output will be `{‘virat’: [50, 30], ‘rohit’: [40, 10]}`. The values for the keys ‘virat’ and ‘rohit’ are grouped together as lists.

9). What is the output of the following code?

A = { ‘a’: ’30’, ‘b’: ’20’, ‘c’: ’10’ }
D1 = {}
for k,v in A.items():
    D1[k] = int(v)
print(D1)

a) D1 = {‘a’: 30, ‘b’: 20, ‘c’: 10}
b) D1 = {‘a’: ’30’, ‘b’: ’20’, ‘c’: ’10’}
c) D1 = {‘a’: 3, ‘b’: 2, ‘c’: 1}
d) D1 = {’30’: ‘a’, ’20’: ‘b’, ’10’: ‘c’}

Corresct answer is: a) D1 = {‘a’: 30, ‘b’: 20, ‘c’: 10}
Explanation: The code initializes an empty dictionary `D1`. It then iterates over the items of dictionary `A` using the `items()` method, which provides key-value pairs. In each iteration, it assigns the key to variable `k` and the value to variable `v`. The line `D1[k] = int(v)` assigns the key-value pair to `D1`, where the value is converted to an integer using the `int()` function. Therefore, the resulting `D1` dictionary will have the same keys as `A`, but with the values converted to integers. Thus, the content of `D1` will be {‘a’: 30, ‘b’: 20, ‘c’: 10}.

10). What is the output of the following code?

B = {‘a’: ‘3.33’, ‘b’: ‘20.50’, ‘c’: ‘12.5’}
D2 = {}
for key, val in B.items():
    D2[key] = float(val)
print(D2)

a) {‘a’: ‘3.33’, ‘b’: ‘20.50’, ‘c’: ‘12.5’}
b) {‘a’: 3.33, ‘b’: 20.5, ‘c’: 12.5}
c) {‘a’: ‘3.33’, ‘b’: ‘20.50’, ‘c’: ‘12.5’}
d) {‘a’: ‘3.33’, ‘b’: ‘20.50’, ‘c’: ‘12.5’}

Corresct answer is: b) {‘a’: 3.33, ‘b’: 20.5, ‘c’: 12.5}
Explanation: The code initializes an empty dictionary `D2`. It then iterates through the key-value pairs of dictionary `B` using the `items()` method. For each key-value pair, the code converts the value from string to float using the `float()` function and assigns the converted value to the corresponding key in `D2`. Finally, it prints the contents of `D2`. As a result, the output will be `{‘a’: 3.33, ‘b’: 20.5, ‘c’: 12.5}` where the values are converted to floating-point numbers.

11). What is the output of the following code?

D1 = {‘virat’: [50, 30], ‘rohit’: [40, 10]}
for key in D1:
    D1[key].clear()
print(D1)

a) {}
b) {‘virat’: [], ‘rohit’: []}
c) {‘virat’: None, ‘rohit’: None}
d) Error

Corresct answer is: b) {‘virat’: [], ‘rohit’: []}
Explanation: The given code iterates over each key in the dictionary `D1` using the `for` loop. Inside the loop, the `clear()` method is called on each list value associated with the keys in `D1`. The `clear()` method removes all elements from a list, making it an empty list. After the loop completes, the dictionary `D1` will have empty lists as the values for both ‘virat’ and ‘rohit’ keys. 

12). What will be the output of the given code snippet?

D1 = [{‘t20′:50,’odi’:70},{‘t20′:40,’odi’:10},{‘t20′:30,’odi’:0},{‘t20′:45,’odi’:65}]
l = []

for ele in D1:
    for key,val in ele.items():
        if key == ‘odi’:
            l.append(val)
print(l)

a) [70, 10, 0, 65]
b) [70, 40, 30, 45]
c) [50, 40, 30, 45]
d) [70, 45]

Corresct answer is: a) [70, 10, 0, 65]
Explanation: The code initializes an empty list `l`. It then iterates over each dictionary element `ele` in the list `D1`. For each dictionary, it checks if the key is ‘odi’. If it is, the corresponding value is appended to the list `l`. In this case, the values of ‘odi’ keys in the dictionaries are [70, 10, 0, 65], which results in the output [70, 10, 0, 65].

13). What is the output of the following code?

D1 = {1:’sql’,2:’tools’,3:’python’}
D2 = {}

for val in D1.values():
    D2[val] = len(val)
print(D2)

a) {1: 3, 2: 5, 3: 6}
b) {‘sql’: 3, ‘tools’: 5, ‘python’: 6}
c) {1: ‘sql’, 2: ‘tools’, 3: ‘python’}
d) {‘sql’: 1, ‘tools’: 2, ‘python’: 3}

Corresct answer is: b) {‘sql’: 3, ‘tools’: 5, ‘python’: 6}
Explanation: The code initializes an empty dictionary `D2` and iterates over the values of `D1` using a for loop. For each value `val`, a key-value pair is added to `D2` where the key is `val` and the value is the length of `val`. In this case, the length of ‘sql’ is 3, the length of ‘tools’ is 5, and the length of ‘python’ is 6. 

14). What is the output of the following code?

D1 = {‘sqatools’: 8, ‘python’: 6}
l = [1, 2]

res = {}
for key, ele in zip(l, D1.items()):
    res[key] = dict([ele])
print(res)

a) {1: {‘sqatools’: 8}, 2: {‘python’: 6}}
b) {1: {‘sqatools’: 6}, 2: {‘python’: 8}}
c) {1: (‘sqatools’, 8), 2: (‘python’, 6)}
d) {1: (‘sqatools’, 6), 2: (‘python’, 8)}

Corresct answer is: a) {1: {‘sqatools’: 8}, 2: {‘python’: 6}}
Explanation: The code initializes an empty dictionary `res`. The `zip` function pairs the elements of the list `l` with the items (key-value pairs) of the dictionary `D1`. The loop iterates over these pairs. In each iteration, the line `res[key] = dict([ele])` creates a new dictionary using the `dict()` constructor with a single item `ele`, which is a key-value pair from `D1`. This newly created dictionary is assigned as the value to the key `key` in the `res` dictionary.

15). What is the output of the following code?

D1 = {1:’sqatools is best’,2:’for learning python’}
substr = [‘best’,’excellent’]
res = dict()

for key, val in D1.items():
    if not any(ele in val for ele in substr):
        res[key] = val
print(res)

a) {1: ‘sqatools is best’, 2: ‘for learning python’}
b) {2: ‘for learning python’}
c) {1: ‘sqatools is best’}
d) {}

Corresct answer is: b) {2: ‘for learning python’}
Explanation: The code is creating an empty dictionary res and iterating over the key-value pairs in D1 using D1.items(). Inside the loop, it checks if any element in substr is present in the value (val) of each key-value pair. If none of the elements in substr are found in the value, the key-value pair is added to the res dictionary.

16). Which two keys are printed when executing the following code?

D1 = {‘a’:18, ‘b’:50, ‘c’:36, ‘d’:47, ‘e’:60}
result = sorted(D1, key=D1.get, reverse=True)
print(result[:2])

a) ‘e’, ‘b’
b) ‘e’, ‘d’
c) ‘b’, ‘d’
d) ‘b’, ‘c’

Corresct answer is: a) ‘e’, ‘b’
Explanation: The code sorts the keys in the dictionary `D1` based on their corresponding values in descending order. The `key` parameter in the `sorted()` function specifies that the sorting should be based on the values obtained by calling `D1.get()` for each key. The `reverse=True` parameter ensures the sorting is in descending order. After sorting, the `result` variable will contain the keys in the following order: ‘e’, ‘b’, ‘d’, ‘c’, ‘a’. The `print(result[:2])` statement prints the first two elements of the `result` list, which are ‘e’ and ‘d’.

17). What is the output of the following code?

from collections import Counter
D1 = {‘a’: 10, ‘b’: 20, ‘c’: 25, ‘d’: 10, ‘e’: 30, ‘f’: 20}

result = Counter(D1.values())
print(result)

a) {10: 2, 20: 2, 25: 1, 30: 1}
b) {2: 10, 20: 1, 25: 1, 30: 1}
c) {1: 2, 2: 2, 10: 2, 20: 2, 25: 1, 30: 1}
d) {10: 1, 20: 1, 25: 1, 30: 1}

Corresct answer is: a) {10: 2, 20: 2, 25: 1, 30: 1}
Explanation: The Counter class from the collections module is used to count the occurrences of elements in an iterable. In this case, `D1.values()` returns an iterable of the dictionary values. The output is a dictionary where the keys represent the unique values from `D1.values()`, and the values represent the count of each unique value in the iterable. The dictionary `D1` has the following values: [10, 20, 25, 10, 30, 20]. The count of `10` is `2`, the count of `20` is `2`, the count of `25` is `1`, and the count of `30` is `1`. 

18). What is the output of the following code?

from itertools import product
D1 = {1:[‘Virat Kohli’], 2:[‘Rohit Sharma’], 3:[‘Hardik Pandya’]}

for sub in product(*D1.values()):
    result = [dict(zip(D1, sub))]
print(result)

a) [{‘Virat Kohli’, ‘Rohit Sharma’, ‘Hardik Pandya’}]
b) [{‘1’: ‘Virat Kohli’}, {‘2’: ‘Rohit Sharma’}, {‘3’: ‘Hardik Pandya’}]
c) [{‘1’: ‘Virat Kohli’, ‘2’: ‘Rohit Sharma’, ‘3’: ‘Hardik Pandya’}]
d) [{‘1’, ‘2’, ‘3’}, {‘Virat Kohli’, ‘Rohit Sharma’, ‘Hardik Pandya’}]

Corresct answer is: c) [{‘1’: ‘Virat Kohli’, ‘2’: ‘Rohit Sharma’, ‘3’: ‘Hardik Pandya’}]
Explanation: The code uses the `itertools.product` function to generate all possible combinations of the values from the dictionary `D1`. The `product(*D1.values())` part unpacks the values of `D1` as arguments to `product` function. Each combination is then converted into a dictionary using `dict(zip(D1, sub))`, where `sub` represents a combination of values.

19). What is the output of the following code?

l = [‘abc’, ‘defg’, ‘hijkl’]
D1 = {}

for val in l:
    D1[len(val)] = val

print(D1)

a) {‘abc’: 3, ‘defg’: 4, ‘hijkl’: 5}
b) {3: ‘abc’, 4: ‘defg’, 5: ‘hijkl’}
c) {0: ‘abc’, 1: ‘defg’, 2: ‘hijkl’}
d) {‘abc’: 0, ‘defg’: 1, ‘hijkl’: 2}

Corresct answer is: b) {3: ‘abc’, 4: ‘defg’, 5: ‘hijkl’}
Explanation: The code creates an empty dictionary D1 and iterates over the list l. For each value in l, it assigns the value as a key to D1 and the length of the value as the corresponding value. Therefore, the output is {3: ‘abc’, 4: ‘defg’, 5: ‘hijkl’}.

20). What is the output of the following code?

A = {‘name’: 1, ‘age’: 2}
B = {‘name’: 1, ‘age’: 2, ‘course’: 3, ‘institute’: 4}

count_a = len(A)
count_b = len(B)

if count_a > count_b:
    print(“1st dictionary has maximum pairs”, count_a)
else:
    print(“2nd dictionary has maximum pairs”, count_b)

a) “1st dictionary has maximum pairs”, 2
b) “1st dictionary has maximum pairs”, 4
c) “2nd dictionary has maximum pairs”, 4
d) “2nd dictionary has maximum pairs”, 2

Corresct answer is: c) “2nd dictionary has maximum pairs”, 2
Explanation: In this code, the length (number of key-value pairs) of dictionary A is calculated and stored in the variable `count_a`. Similarly, the length of dictionary B is calculated and stored in `count_b`. Since `count_a` is not greater than `count_b`, the condition `count_a > count_b` evaluates to `False`. 

21). What will be the output of the following code?

D1 = {‘xyz’: [20, 40], ‘abc’: [10, 30]}
D2 = {}

for k, v in D1.items():
    for ele in v:
        D2[ele] = [k]
print(D2)

a) {20: [‘xyz’], 40: [‘xyz’], 10: [‘abc’], 30: [‘abc’]}
b) {20: [‘abc’], 40: [‘abc’], 10: [‘xyz’], 30: [‘xyz’]}
c) {‘xyz’: [20, 40], ‘abc’: [10, 30]}
d) {‘abc’: [20, 40], ‘xyz’: [10, 30]}

Corresct answer is: a) {20: [‘xyz’], 40: [‘xyz’], 10: [‘abc’], 30: [‘abc’]}
Explanation: The code iterates over the key-value pairs in D1 using the items() method. For each key-value pair, it then iterates over the elements in the value list. In each iteration, it assigns the key as the value of D2 with the current element as the key. Since the elements in the value lists are 20, 40, 10, and 30, the corresponding keys in D2 will be 20, 40, 10, and 30. Since the values in D1 are lists, and a new list is assigned as the value in D2, each key in D2 will have a list as its value. The list contains the corresponding key from D1. 

22). What is the output of the following code?

D1 = {‘a’: 19, ‘b’: 20, ‘c’: 21, ‘d’: 20}
l = list(D1.items())
print(l)

a) [(‘a’, 19), (‘b’, 20), (‘c’, 21), (‘d’, 20)]
b) [(‘a’, 19), (‘c’, 21), (‘b’, 20), (‘d’, 20)]
c) [(‘b’, 20), (‘a’, 19), (‘c’, 21), (‘d’, 20)]
d) [(‘c’, 21), (‘d’, 20), (‘b’, 20), (‘a’, 19)]

Corresct answer is: a) [(‘a’, 19), (‘b’, 20), (‘c’, 21), (‘d’, 20)]
Explanation: The code converts the dictionary `D1` into a list of tuples using the `items()` method. The `items()` method returns a view object that contains key-value pairs of the dictionary. The list is created from this view object using the `list()` function. The order of the items in the list corresponds to the order in which they were added to the dictionary. In this case, the order is preserved, resulting in `[(‘a’, 19), (‘b’, 20), (‘c’, 21), (‘d’, 20)]` as the output.

23). What is the output of the following code?

Name = [‘Virat’, ‘Rohit’]
Defaults = {‘sport’: ‘cricket’, ‘salary’: 100000}
D1 = {}

for name in Name:
    D1[name] = Defaults
print(D1)

a) {‘Virat’: {‘sport’: ‘cricket’, ‘salary’: 100000}, ‘Rohit’: {‘sport’: ‘cricket’, ‘salary’: 100000}}
b) {‘Virat’: ‘cricket’, ‘Rohit’: ‘cricket’}
c) {‘Virat’: ‘cricket’, ‘Rohit’: 100000}
d) {‘Virat’: ‘Virat’, ‘Rohit’: ‘Rohit’}

Corresct answer is: a) {‘Virat’: {‘sport’: ‘cricket’, ‘salary’: 100000}, ‘Rohit’: {‘sport’: ‘cricket’, ‘salary’: 100000}}
Explanation: The code initializes an empty dictionary D1. It then iterates over the elements in the Name list. For each element, it assigns the value of the Defaults dictionary to the corresponding key in D1. Therefore, the output is {‘Virat’: {‘sport’: ‘cricket’, ‘salary’: 100000}, ‘Rohit’: {‘sport’: ‘cricket’, ‘salary’: 100000}}, where both keys in D1 have the same dictionary value from Defaults.

24). What is the output of the following code?

D1 = {‘a’:19,’b’: 20,’c’:21,’d’:20}
D1[‘e’] = D1.pop(‘d’)
print(D1)

a) {‘a’: 19, ‘b’: 20, ‘c’: 21, ‘d’: 20}
b) {‘a’: 19, ‘b’: 20, ‘c’: 21, ‘e’: 20}
c) {‘a’: 19, ‘b’: 20, ‘c’: 21}
d) {‘a’: 19, ‘b’: 20, ‘c’: 21, ‘e’: 21}

Corresct answer is: b) {‘a’: 19, ‘b’: 20, ‘c’: 21, ‘e’: 20}
Explanation: The code snippet creates a dictionary `D1` with four key-value pairs: {‘a’: 19, ‘b’: 20, ‘c’: 21, ‘d’: 20}. The statement `D1[‘e’] = D1.pop(‘d’)` removes the key-value pair with the key ‘d’ from the dictionary `D1` using the `pop()` method. The `pop()` method returns the value associated with the popped key, which is 20 in this case. Then, a new key-value pair is added to the dictionary with the key ‘e’ and the value returned from `D1.pop(‘d’)`, which is 20.

25). What is the output of the following code?

D1 = {‘a’: [6, 7, 2, 8, 1], ‘b’: [2, 3, 1, 6, 8, 10], ‘d’: [1, 8, 2, 6, 9]}
l = []

for v in D1.values():
    for num in v:
        if num not in l:
            l.append(num)
print(“Sum: “, sum(l))

a) Sum: 0
b) Sum: 3
c) Sum: 39
d) Sum: 49

Corresct answer is: c) Sum: 46
Explanation: The code iterates over the values of the dictionary `D1`. It then iterates over the numbers in each value and checks if the number is already present in the list `l`. If not, it appends the number to `l`. Finally, the sum of all the unique numbers in `l` is calculated using `sum(l)`. In this case, the unique numbers are `[6, 7, 2, 8, 1, 3, 10, 9]`, and their sum is 46. 

Leave a Comment