Python Function MCQ : Set 2

Python Function MCQ

1). What is the purpose of the “return” statement in Python?

a) It defines a loop.
b) It handles exceptions.
c) It terminates the execution of a loop.
d) It specifies the value to be returned by a function.

Correct answer is: d) It specifies the value to be returned by a function.
Explanation: The “return” statement is used to specify the value that a function should return when it is called.

2). Which of the following is a valid way to define a default argument in a function?

a) def my_func(x = 0):
b) def my_func(x, default=0):
c) def my_func(default=0, x):
d) def my_func(x = 0, default):

Correct answer is: a) def my_func(x = 0):
Explanation: Option a) is a valid way to define a default argument in a function. The default value is specified after the “=” sign.

3). What is the purpose of the “reduce()” function in Python?

a) It applies a function to every item in an iterable.
b) It removes duplicates from an iterable.
c) It filters out elements from an iterable based on a condition.
d) It performs a cumulative computation on an iterable.

Correct answer is: d) It performs a cumulative computation on an iterable.
Explanation: The “reduce()” function is used to perform a cumulative computation on an iterable by applying a specified function to the elements.

4). What is the function header?

a) The name of the function and the list of parameters that the function takes.
b) The list of parameters that the function takes.
c) The body of the function.
d) The return value of the function.

Correct answer is: a) The name of the function and the list of parameters that the function takes.

5). What is the body of a function?

a) The code that is executed when the function is called.
b) The list of parameters that the function takes.
c) The return value of the function.
d) The name of the function.

Correct answer is: a) The code that is executed when the function is called.

6). What is a parameter?

a) A variable that is defined inside a function.
b) A variable that is used to store the return value of a function.
c) A variable that is passed to a function.
d) A variable that is used to control the flow of execution of a function.

Correct answer is: c) A variable that is passed to a function.

7). What is the difference between a global variable and local variable?

a) A local variable is defined inside a function, while a global variable is defined outside of a function.
b) A local variable can only be accessed inside the function that defines it, while a global variable can be accessed anywhere in the program.
c) A local variable is created when the function is called, and it is destroyed when the function returns. A global variable is created when the program starts, and it exists until the program ends.
d) All of the above.

Correct answer is: d) All of the above.

8). What is the difference between a built-in function and a user-defined function?

a) A built-in function is a function that is provided by the Python language, while a user-defined function is a function that is defined by the user.
b) A built-in function cannot be modified, while a user-defined function can be modified.
c) A built-in function can only be called from within a function, while a user-defined function can be called from anywhere in the program.
d) All of the above.

Correct answer is: d) All of the above.

9). What is the advantage of using functions?

a) Functions make code more readable and maintainable.
b) Functions can be reused in different parts of the program.
c) Functions can help to improve performance.
d) All of the above.

Correct answer is: d) All of the above.

10). What is the disadvantage of using functions?

a) Functions can make code more complex.
b) Functions can make code less efficient.
c) Functions can make code more difficult to debug.
d) None of the above.

Correct answer is: d) None of the above.

11). What is the purpose of the “zip()” function in Python?

a) It combines two or more iterables element-wise.
b) It compresses data into a ZIP file.
c) It returns the size of an iterable.
d) It reverses the order of elements in an iterable.

Correct answer is: a) It combines two or more iterables element-wise.
Explanation: The “zip()” function is used to combine two or more iterables element-wise, creating an iterator of tuples.

12). Which of the following is a valid way to access the documentation string of a function in Python?

a) help(my_function)
b) my_function.__doc__
c) my_function.document
d) All of the above

Correct answer is: d) All of the above
Explanation: All the given options are valid ways to access the documentation string (docstring) of a function in Python.

13). Which of the following is a valid way to define a recursive function in Python?

a) def my_func():
b) def my_func(x):
c) def my_func():
d) def my_func(x = 0):

Correct answer is: b) def my_func(x):
Explanation: Option b) is a valid way to define a recursive function in Python. The function should have at least one parameter to enable recursive calls with different arguments.

14). Which of the following is a valid way to define a lambda function in Python?

a) lambda x: x + 1
b) def lambda(x): return x + 1
c) def my_func(x): return x + 1
d) lambda: return x + 1

Correct answer is: a) lambda x: x + 1
Explanation: Option a) is a valid way to define a lambda function in Python. It takes a parameter `x` and returns `x + 1`.

15). What is the purpose of the “filter()” function in Python?

a) It applies a function to every item in an iterable.
b) It removes duplicates from an iterable.
c) It filters out elements from an iterable based on a condition.
d) It counts the number of occurrences of an element in an iterable.

Correct answer is: c) It filters out elements from an iterable based on a condition.
Explanation: The “filter()” function is used to filter out elements from an iterable based on a specified condition.

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

def func(x):
    return x * 3

result = func(“abc”)
print(result)

a) a
b) abc
c) abcabcabc
d) None

Correct answer is: c) abcabcabc
Explanation: The function func multiplies the input string x by 3. In this case, “abc” multiplied by 3 results in “abcabcabc”.

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

def func(x):
    return x * 2

value = 4
result = func(value)
print(result)

a) 3
b) 8
c) 9
d) None

Correct answer is: b) 8
Explanation: The variable value is passed to the function func, and the function returns the value of x multiplied by 2. In this case, value is 4, so the function returns 4 * 2 = 8.

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

def func(x):
    if x == “”:
        return “Empty”
    else:
        return “Not empty”

result = func(“”)
print(result)

a) Empty
b) Not empty
c) Error
d) None

Correct answer is: a) Empty
Explanation: The function func checks if the input string x is empty. In this case, since x is an empty string, it returns “Empty”.

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

def func(x):
    return len(x)

result = func([1, 2, 3, 4])
print(result)

a) 1
b) 2
c) 3
d) 4

Correct answer is: d) 4
Explanation: The function func returns the length of the input list x using the “len()” function. In this case, the list has 4 elements, so the output is 4.

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

def func(x):
    return x[::-1]

result = func(“Python”)
print(result)

a) nohtyP
b) P
c) Python
d) None

Correct answer is: a) nohtyP
Explanation: The function func returns the reverse of the input string x using slicing with a step of -1. In this case, “Python” reversed becomes “nohtyP”.

Python Function MCQ : Set 1

Python Function MCQ

1). Which keyword is used to define a function in Python?

a) def
b) func
c) define
d) function

Correct answer is: a) def
Explanation: The keyword “def” is used to define a function in Python.

2). In a function what is the purpose of a return statement?

a) It defines the function name.
b) It calls another function.
c) It specifies the input parameters.
d) It returns a value from the function.

Correct answer is: d) It returns a value from the function.
Explanation: The return statement is used to specify the value that should be returned from the function when it is called.

3). Which of the following is a valid way to call a function in Python?

a) function_name()
b) functionName()
c) FunctionName()
d) All of the above.

Correct answer is: d) All of the above.
Explanation: All of the given options are valid ways to call a function in Python.

4). What is the purpose of the “pass” statement in Python?

a) It is used to define an empty function.
b) It is used to skip the execution of a function.
c) It is used to indicate the end of a function.
d) It is used to define a placeholder in a function.

Correct answer is: d) It is used to define a placeholder in a function.
Explanation: The “pass” statement is used as a placeholder when you want to define a function without any implementation.

5). Which scope in Python can access variables defined inside a function?

a) Global scope
b) Local scope
c) Built-in scope
d) None of the above

Correct answer is: a) Global scope
Explanation: Variables defined inside a function have local scope and can only be accessed within that function, unless they are explicitly marked as global.

6). What happens if a function is called with fewer arguments than specified in the function definition?

a) An error is raised.
b) The function will run without any issues.
c) The missing arguments will be assigned default values.
d) The function will return None.

Correct answer is: a) An error is raised.
Explanation: If a function is called with fewer arguments than specified in the function definition, a TypeError will be raised.

7). What is the purpose of the “lambda” keyword in Python?

a) It defines a lambda expression.
b) It is used to create a new function.
c) It is used to define the main function.
d) It is used to import external modules.

Correct answer is: a) It defines a lambda expression.
Explanation: The “lambda” keyword is used to define anonymous functions, also known as lambda expressions.

8). Which of the following is a valid way to pass arguments to a function?

a) Positional arguments
b) Keyword arguments
c) Default arguments
d) All of the above

Correct answer is: d) All of the above
Explanation: All the options (positional, keyword, and default arguments) are valid ways to pass arguments to a function.

9). What is the maximum number of return statements allowed in a function?

a) 1
b) 2
c) 3
d) There is no limit.

Correct answer is: d) There is no limit.
Explanation: There is no limit to the number of return statements in a function. However, only one return statement is executed during the function call.

10). What is the purpose of the “map” function in Python?

a) It applies a function to every item in an iterable.
b) It returns the maximum value from an iterable.
c) It converts an iterable to a list.
d) It sorts the items in an iterable.

Correct answer is: a) It applies a function to every item in an iterable.
Explanation: The “map” function is used to apply a given function to each item of an iterable and returns an iterator with the results.

11). Which of the following is a recursive function?

a) A function that calls itself.
b) A function that uses a loop.
c) A function that imports another module.
d) A function that returns multiple values.

Correct answer is: a) A function that calls itself.
Explanation: It is a function that calls itself either directly or indirectly.

12). Which built-in function is used to find the length of an object?

a) count()
b) length()
c) size()
d) len()

Correct answer is: d) len()
Explanation: The `len()` function is used to find the length of an object, such as a string, list, or tuple.

13). What is the purpose of the “global” keyword in Python?

a) It defines a global variable.
b) It imports a module.
c) It creates a new function.
d) It raises an error.

Correct answer is: a) It defines a global variable.
Explanation: The “global” keyword is used to indicate that a variable is defined in the global scope, allowing it to be accessed from any part of the program.

14). Which of the following is NOT a valid way to define a function in Python?

a) def my_function():
b) define my_function():
c) my_function = def():
d) lambda x: x + 1

Correct answer is: c) my_function = def():
Explanation: The option c) is not a valid way to define a function in Python. The correct syntax is `def function_name():`.

15). Which of the following is NOT a valid function call in Python?

a) my_function(1, 2)
b) my_function(x=1, y=2)
c) my_function(1, y=2)
d) my_function(x=1, 2)

Correct answer is: d) my_function(x=1, 2)
Explanation: In a function call, keyword arguments must follow positional arguments. In option d), a positional argument is followed by a keyword argument, which is not valid.

16). What is the purpose of the “__init__” method in a Python class?

a) It defines the class name.
b) It initializes the object’s state.
c) It imports external modules.
d) It defines class methods.

Correct answer is: b) It initializes the object’s state.
Explanation: The method “__init__” is a method in Python classes that is called when an object is created. It initializes the object’s state.

17). Which of the following is a built-in function in Python for sorting?

a) sort()
b) sorted()
c) order()
d) arrange()

Correct answer is: b) sorted()
Explanation: The `sorted()` function is a built-in function in Python that is used to sort iterables, such as lists or tuples.

18). What is the purpose of the “isinstance()” function in Python?

a) It checks if two objects are equal.
b) It checks if an object is an instance of a class.
c) It converts an object to a different type.
d) It finds the index of an element in a list.

Correct answer is: b) It checks if an object is an instance of a class.
Explanation: The function `isinstance()` is used to check if an object is an instance of a specified class or its subclasses.

19). Which of the following is a valid way to define a default argument in a function?

a) def my_func(x = 0):
b) def my_func(x, default=0):
c) def my_func(default=0, x):
d) def my_func(x = 0, default):

Correct answer is: a) def my_func(x = 0):
Explanation: Option a) is a valid way to define a default argument in a function. The default value is specified after the “=” sign.

20). What is the purpose of the “enumerate()” function in Python?

a) It counts the number of occurrences of an element in an iterable.
b) It returns a reversed version of an iterable.
c) It assigns indices to items in an iterable.
d) It removes duplicates from an iterable.

Correct answer is: c) It assigns indices to items in an iterable.
Explanation: The “enumerate()” function is used to assign indices to items in an iterable, creating tuples of the form (index, item).

Python Set MCQ : Set 4

Python Set MCQ

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

a = {1, 2, 4, 5, 7, 8, 9}
print(“Original set1: “, a)
print(type(a))

a) Original set1: {1, 2, 4, 5, 7, 8, 9}
\<class ‘set’>
b) Original set1: {1, 2, 4, 5, 7, 8, 9}
\<class ‘list’>
c) Original set1: {1, 2, 4, 5, 7, 8, 9}
\<class ‘tuple’>
d) Original set1: {1, 2, 4, 5, 7, 8, 9}
\<class ‘dict’>

Correct answer is: a) Original set1: {1, 2, 4, 5, 7, 8, 9} \<class ‘set’>
Explanation: The code initializes a set named ‘a’ with the elements 1, 2, 4, 5, 7, 8, and 9. The print() function is then used to display the original set, which outputs {1, 2, 4, 5, 7, 8, 9}. The type() function is used to determine the data type of the set ‘a’, which is a set (class ‘set’).

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

a = {1, 2, 4, 5, 7, 8, 9}
print(“Original set1: “, a)
b = frozenset(a)
print(b)

a) Original set1: {1, 2, 4, 5, 7, 8, 9}
frozenset({1, 2, 4, 5, 7, 8, 9})
b) Original set1: {1, 2, 4, 5, 7, 8, 9}
frozenset([1, 2, 4, 5, 7, 8, 9])
c) Original set1: {1, 2, 4, 5, 7, 8, 9}
frozenset((1, 2, 4, 5, 7, 8, 9))
d) Original set1: {1, 2, 4, 5, 7, 8, 9}
frozenset({1: None, 2: None, 4: None, 5: None, 7: None, 8: None, 9: None})

Correct answer is: c) Original set1: {1, 2, 4, 5, 7, 8, 9}
frozenset({1, 2, 4, 5, 7, 8, 9})
Explanation: The code initializes a set `a` with elements 1, 2, 4, 5, 7, 8, and 9. The line `b = frozenset(a)` creates a frozen set `b` from `a`. The `frozenset()` function returns an immutable frozenset object. The output will be “Original set1: {1, 2, 4, 5, 7, 8, 9}” followed by “frozenset({1, 2, 4, 5, 7, 8, 9})”.

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

a = {1,2,4,6}
b = {7,8,9,6}
c = {5,8,9}
print(“Original set1: “,a)
print(“Original set2: “,b)
print(“Original set3: “,c)
print(“Difference between above sets: “)
print(a.difference(b.difference(c)))

a) Original set1: {1, 2, 4, 6}
Original set2: {7, 8, 9, 6}
Original set3: {5, 8, 9}
Difference between above sets: {1, 2, 4}
b) Original set1: {1, 2, 4, 6}
Original set2: {7, 8, 9, 6}
Original set3: {5, 8, 9}
Difference between above sets: {1, 2, 4, 6, 7, 8, 9}
c) Original set1: {1, 2, 4, 6}
Original set2: {7, 8, 9, 6}
Original set3: {5, 8, 9}
Difference between above sets: {1, 2, 4, 5, 6, 7, 8, 9}
d) Original set1: {1, 2, 4, 6}
Original set2: {7, 8, 9, 6}
Original set3: {5, 8, 9}
Difference between above sets: {5, 7}

Correct answer is: a) Original set1: {1, 2, 4, 6}
Original set2: {7, 8, 9, 6}
Original set3: {5, 8, 9}
Difference between above sets: {1, 2, 4}
Explanation: The code demonstrates the difference between sets using the difference() method. The difference() method is applied to the set ‘a’ with the argument ‘b.difference(c)’, which computes the difference between set ‘b’ and set ‘c’. Then, this difference is subtracted from set ‘a’ using the difference() method. The resulting set contains the elements that are present in ‘a’ but not in ‘b’ or ‘c’, which in this case is {1, 2, 4}.

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

a = {1,2,4,6}
b = {7,8,9,6}
c = {5,8,9,6}
print(“Original set1: “,a)
print(“Original set2: “,b)
print(“Original set3: “,c)
print(“Intersection between above sets: “)
print(a.intersection(b.intersection(c)))

a) {6}
b) {1, 2, 4, 6}
c) {6, 8, 9}
d) {6, 8, 9, 5}

Correct answer is: a) {6}
Explanation: The code calculates the intersection between sets a, b, and c using the intersection() method. First, b.intersection(c) finds the common elements between sets b and c, which results in {6, 8, 9}. Then, a.intersection(b.intersection(c)) finds the common elements between set a and the result of the previous intersection, which is {6}.

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

a = {1,2,4,6}
b = {7,8,9,6}
c = {5,8,9,6}
print(“Original set1: “,a)
print(“Original set2: “,b)
print(“Original set3: “,c)
print(“Difference between above sets: “)
print(a.union(b.union(c)))

a) {1, 2, 4, 5, 6, 7, 8, 9}
b) {1, 2, 4, 6, 7, 8, 9}
c) {1, 2, 4, 5, 6, 7}
d) {1, 2, 4, 6}

Correct answer is: a) {1, 2, 4, 5, 6, 7, 8, 9}
Explanation: The union() method is used to find the union of multiple sets. In this case, we are finding the union of set a, set b, and set c. The resulting set contains all the unique elements from all the sets involved. Therefore, the output will be {1, 2, 4, 5, 6, 7, 8, 9}.

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

String = “Learning python is fun”
Set = {“fun”,”python”}
count = 0
for word in Set:
    if word in String:
        count += 1
if count > 0:
print(“An element in a set is a substring of a given string”)
else:
print(“An element in a set is not a substring of a given string”)

a) An element in a set is a substring of a given string
b) An element in a set is not a substring of a given string
c) String: Learning python is fun
Set: {‘fun’, ‘python’}
d) String: “Learning python is fun”
Set: {“fun”,”python”}

Correct answer is: a) An element in a set is a substring of a given string
Explanation: The code checks if any element in the set is a substring of the given string. In this case, both “fun” and “python” are substrings of the string “Learning python is fun”. Therefore, the count variable is incremented, and the condition count > 0 is satisfied. As a result, the output will be “An element in a set is a substring of a given string”.

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

Set = {1, 2, 4, 6}
print(“Set: “, Set)
List = list(Set)
print(“The index of 4: “, List.index(4))

a) Set: {1, 2, 4, 6} | The index of 4: 2
b) Set: {1, 2, 4, 6} | The index of 4: 3
c) Set: [1, 2, 4, 6] | The index of 4: 2
d) Set: [1, 2, 4, 6] | The index of 4: 3

Correct answer is: a) Set: {1, 2, 4, 6} | The index of 4: 2
Explanation: The code initializes a set named “Set” with the elements 1, 2, 4, and 6. The set is then converted to a list using the list() function and stored in the variable “List”. When using the index() method on the list “List” and passing the argument 4, it returns the index position of the element 4, which is 2.

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

a = {1, 2, 4, 6}
print(“Original set:”, a)
Dict = {}
for ele in a:
    Dict[ele] = {}
print(“Dictionary:”, Dict)

a) Original set: {1, 2, 4, 6} Dictionary: {1: {}, 2: {}, 4: {}, 6: {}}
b) Original set: {1, 2, 4, 6} Dictionary: {1: {}, 2: {}, 3: {}, 4: {}, 5: {}, 6: {}}
c) Original set: {1, 2, 4, 6} Dictionary: {1: {}, 2: {}, 4: {}, 6: {}, 8: {}}
d) Original set: {1, 2, 4, 6} Dictionary: {1: {}, 2: {}, 4: {}, 6: {}, 1: {}}

Correct answer is: a) Original set: {1, 2, 4, 6} Dictionary: {1: {}, 2: {}, 4: {}, 6: {}}
Explanation: In the code, a set `a` is defined with elements [1, 2, 4, 6]. The set is then printed as “Original set: {1, 2, 4, 6}”. An empty dictionary `Dict` is created. The for loop iterates over each element in set `a` and assigns an empty dictionary as a value to each element in the `Dict` dictionary. Finally, the dictionary is printed as “Dictionary: {1: {}, 2: {}, 4: {}, 6: {}}”.

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

Set = set()
for num in range(1, 21):
    if num % 2 == 0:
        Set.add(num)
print(“Set of even numbers:”, Set)

a) Set of even numbers: {2, 4, 6, 8, 10, 12, 14, 16, 18, 20}
b) Set of even numbers: {1, 3, 5, 7, 9, 11, 13, 15, 17, 19}
c) Set of even numbers: {}
d) Set of even numbers: {2, 4, 6, 8, 10, 12, 14, 16, 18}

Correct answer is: a) Set of even numbers: {2, 4, 6, 8, 10, 12, 14, 16, 18, 20}
Explanation: The given code initializes an empty set, `Set`. It then iterates over the numbers from 1 to 20 using a `for` loop. For each number, if the number is divisible by 2 (i.e., an even number), it adds the number to the set using the `add()` method. Finally, it prints the set of even numbers, which includes all even numbers from 1 to 20. The correct answer is option a.

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

Set = set()
for num in range(1,21):
    if num%2 != 0:
        Set.add(num)
print(“Set of odd numbers: “, Set)

a) Set of odd numbers: {1, 3, 5, 7, 9, 11, 13, 15, 17, 19}
b) Set of odd numbers: {2, 4, 6, 8, 10, 12, 14, 16, 18, 20}
c) Set of odd numbers: {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20}
d) Set of odd numbers: {}

Correct answer is: a) Set of odd numbers: {1, 3, 5, 7, 9, 11, 13, 15, 17, 19}
Explanation: The code initializes an empty set and then iterates over numbers from 1 to 20. If a number is odd, it is added to the set using the add() method. Finally, the set is printed, showing the set of odd numbers from 1 to 20.

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

Set = {“Shan Rukh Khan”, “Akshay Kumar”, “Tom Hardy”, “Robert Pattinson”}
print(“Set of actors: “, Set)

a) Set of actors: {“Shan Rukh Khan”, “Akshay Kumar”, “Tom Hardy”, “Robert Pattinson”}
b) Set of actors: {“Shan Rukh Khan, Akshay Kumar, Tom Hardy, Robert Pattinson”}
c) Set of actors: {‘Shan Rukh Khan’, ‘Akshay Kumar’, ‘Tom Hardy’, ‘Robert Pattinson’}
d) Set of actors: [‘Shan Rukh Khan’, ‘Akshay Kumar’, ‘Tom Hardy’, ‘Robert Pattinson’]

Correct answer is: c) Set of actors: {‘Shan Rukh Khan’, ‘Akshay Kumar’, ‘Tom Hardy’, ‘Robert Pattinson’}
Explanation: The code defines a set named `Set` with four elements: “Shan Rukh Khan”, “Akshay Kumar”, “Tom Hardy”, and “Robert Pattinson”. When the `print()` function is called, it displays the set of actors enclosed in curly braces and single quotes.

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

Set1 = {“Lord of the Rings”, “Harry Potter and the Sorcerer’s Stone”, “The Magic Tree”, “Tower To The Stars”}
Set2 = {“Wizards of Ice”, “Call of the Forest”, “Lord of the Rings”}
print(“Original Set1: “, Set1)
print(“Original Set2: “, Set2)
print(“Common books: “)
for book_name in Set1:
    if book_name in Set2:
        print(book_name)

a) Original Set1: {“Lord of the Rings”, “Harry Potter and the Sorcerer’s Stone”, “The Magic Tree”, “Tower To The Stars”}
Original Set2: {“Wizards of Ice”, “Call of the Forest”, “Lord of the Rings”}
Common books: Lord of the Rings
b) Original Set1: {“Lord of the Rings”, “Harry Potter and the Sorcerer’s Stone”, “The Magic Tree”, “Tower To The Stars”}
Original Set2: {“Wizards of Ice”, “Call of the Forest”, “Lord of the Rings”}
Common books: Lord of the Rings, The Magic Tree
c) Original Set1: {“Lord of the Rings”, “Harry Potter and the Sorcerer’s Stone”, “The Magic Tree”, “Tower To The Stars”}
Original Set2: {“Wizards of Ice”, “Call of the Forest”, “Lord of the Rings”}
Common books: The Magic Tree
d) Original Set1: {“Lord of the Rings”, “Harry Potter and the Sorcerer’s Stone”, “The Magic Tree”, “Tower To The Stars”}
Original Set2: {“Wizards of Ice”, “Call of the Forest”, “Lord of the Rings”}
Common books: Wizards of Ice

Correct answer is: a) Original Set1: {“Lord of the Rings”, “Harry Potter and the Sorcerer’s Stone”, “The Magic Tree”, “Tower To The Stars”}
Original Set2: {“Wizards of Ice”, “Call of the Forest”, “Lord of the Rings”}
Common books: Lord of the Rings
Explanation: The code compares the elements in Set1 with Set2 and prints the books that exist in both sets. In this case, “Lord of the Rings” is the only book that appears in both sets, so it will be printed as the common book.

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

Set = {“I”, “am”, “Learning”, “Python”}
max_len = 0
max_word = 0
print(“Original Set: “, Set)
for word in Set:
    if len(word) > max_len:
        max_len = len(word)
        max_word = word
print(“Word having maximum length: “, max_word)
print(“Length of the word: “, max_len)

a) Original Set: {“I”, “am”, “Learning”, “Python”}
Word having maximum length: “Learning”
Length of the word: 8
b) Original Set: {“I”, “am”, “Learning”, “Python”}
Word having maximum length: “Python”
Length of the word: 6
c) Original Set: {“I”, “am”, “Learning”, “Python”}
Word having maximum length: “Learning”
Length of the word: 7
d) Original Set: {“I”, “am”, “Learning”, “Python”}
Word having maximum length: “am”
Length of the word: 2

Correct answer is: a) Original Set: {“I”, “am”, “Learning”, “Python”}
Word having maximum length: “Learning”
Length of the word: 8
Explanation: The code initializes the `Set` variable with a set of strings. It then iterates over each word in the set and checks if the length of the current word is greater than the current maximum length (`max_len`). If it is, it updates `max_len` and stores the current word as `max_word`. After the loop, it prints the original set, the word with the maximum length, and the length of that word.

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

a = {1,2,4,5}
b = {2,4}
print(“Original set1: “,a)
print(“Original set2: “,b)
count = 0
for ele in b:
    if ele in a:
        count +=1
if count == len(b):
    print(“b is subset of a”)
else:
    print(“b is not a subset of a”)

a) Original set1: {1, 2, 4, 5} Original set2: {2, 4} \n b is subset of a
b) Original set1: {1, 2, 4, 5} Original set2: {2, 4} \n b is not a subset of a
c) Original set1: {2, 4} Original set2: {1, 2, 4, 5} \n b is subset of a
d) Original set1: {2, 4} Original set2: {1, 2, 4, 5} \n b is not a subset of a

Correct answer is: a) Original set1: {1, 2, 4, 5} Original set2: {2, 4} \n b is a subset of a
Explanation: The code checks if every element in set b is also present in set a. If all elements in b are found in a, then b is considered a subset of a. Otherwise, it is not a subset. In this case, set a contains the elements [1, 2, 4, 5] and set b contains the elements [2, 4]. Since all elements in b (2 and 4) are present in a, the condition count == len(b) is satisfied, and the output is “b is a subset of a”.

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

a = {1,2,4,5}
b = {7,8,9}
print(“Original set1: “,a)
print(“Original set2: “,b)
print(“Are two sets dis-joint: “,a.isdisjoint(b))

a) Original set1: {1, 2, 4, 5} Original set2: {7, 8, 9} Are two sets disjoint: True
b) Original set1: {1, 2, 4, 5} Original set2: {7, 8, 9} Are two sets disjoint: False
c) Original set1: {1, 2, 4, 5} Original set2: {7, 8, 9} Are two sets disjoint: None
d) Error: The code contains a syntax error.

Correct answer is: a) Original set1: {1, 2, 4, 5} Original set2: {7, 8, 9} Are two sets disjoint: True
Explanation: The code initializes two sets, a and b, with the values {1, 2, 4, 5} and {7, 8, 9} respectively. The isdisjoint() method is then used to check if the two sets are disjoint (have no common elements). In this case, the sets have no common elements, so the output will be True.

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

a = {1, 2, 4, 5}
b = {2, 4}
print(“Original set1: “, a)
print(“Original set2: “, b)
print(“b is subset of a: “, b.issubset(a))

a) Original set1: {1, 2, 4, 5}
Original set2: {2, 4}
b is subset of a: True
b) Original set1: {1, 2, 4, 5}
Original set2: {2, 4}
b is subset of a: False
c) Original set1: {1, 2, 4, 5}
Original set2: {2, 4}
b is subset of a: None
d) Error: Invalid syntax in the code.

Correct answer is: a) Original set1: {1, 2, 4, 5}
Original set2: {2, 4}
b is subset of a: True
Explanation: The code defines two sets, `a` and `b`. `a` contains elements [1, 2, 4, 5], while `b` contains elements [2, 4]. The `issubset()` method is then used to check if `b` is a subset of `a`. Since all elements of `b` are present in `a`, the output is `True`.

17). Which statement is used to check if an element exists in a set?

a) if element in set:
b) if element exists(set):
c) if element.has(set):
d) if element.exists(set):

Correct answer is: a) if element in set:
Explanation: The “in” keyword is used to check if an element exists in a set.

18). What is the result of executing the following code:

set = {1, 2, 3}
print(2 in set)?

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

Correct answer is: a) True
Explanation: The “in” keyword checks if the element 2 exists in the set, which returns True.

19). Which method is used to return the maximum element from a set?

a) max()
b) maximum()
c) largest()
d) get_max()

Correct answer is: a) max()
Explanation: The max() function is used to return the maximum element from a set.

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

a = {1, 2, 4, 5, 7, 8, 9}
print(“Original set: “,a)
b = {7,8,9}
for ele in b:
    if ele in a:
        a.remove(ele)
print(“New set: “,a)

a) Original set: {1, 2, 4, 5, 7, 8, 9} New set: {1, 2, 4, 5}
b) Original set: {1, 2, 4, 5, 7, 8, 9} New set: {7, 8, 9}
c) Original set: {1, 2, 4, 5, 7, 8, 9} New set: {1, 2, 4, 5, 8, 9}
d) Original set: {1, 2, 4, 5, 7, 8, 9} New set: {1, 2, 4, 5, 7}

Correct answer is: c) Original set: {1, 2, 4, 5, 7, 8, 9} New set: {1, 2, 4, 5}
Explanation: The code starts with a set `a` containing elements {1, 2, 4, 5, 7, 8, 9}. It then defines another set `b` with elements {7, 8, 9}. The code then iterates over each element in `b` and checks if it exists in `a`. If an element is found in `a`, it is removed using the `remove()` method. After this process, the code prints the updated set `a`.

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

a = {1, 2, 4, 5, 7, 8, 9}
print(“Original set1: “,a)
if len(a) == 0:
    print(“Set is empty”)
else:
    print(“Set is not empty”)

a) Original set1: {1, 2, 4, 5, 7, 8, 9}
Set is empty
b) Original set1: {1, 2, 4, 5, 7, 8, 9}
Set is not empty
c) Original set1: {1, 2, 4, 5, 7, 8, 9}
Error: Set object has no attribute ’empty’
d) Original set1: {1, 2, 4, 5, 7, 8, 9}
Error: Set object has no attribute ‘len’

Correct answer is: b) Original set1: {1, 2, 4, 5, 7, 8, 9}
Set is not empty
Explanation: The code initializes a set a with elements [1, 2, 4, 5, 7, 8, 9]. The len(a) function returns the number of elements in the set, which is not equal to 0 in this case. Therefore, the condition len(a) == 0 evaluates to False. As a result, the code executes the else block and prints “Set is not empty”

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

a = {1, 2, 4, 5, 7, 8, 9}
b = {2,3,4}
print(“Original set1: “,a)
print(“Original set2: “,b)
if a == b:
   print(“Both sets are equal”)
else:
    print(“Both sets are not equal”)

a) Original set1: {1, 2, 4, 5, 7, 8, 9}
Original set2: {2, 3, 4}
Both sets are equal
b) Original set1: {1, 2, 4, 5, 7, 8, 9}
Original set2: {2, 3, 4}
Both sets are not equal
c) Original set1: {1, 2, 4, 5, 7, 8, 9}
Original set2: {2, 3, 4}
Error: Invalid comparison between sets
d) Error: Invalid syntax

Correct answer is: b) Original set1: {1, 2, 4, 5, 7, 8, 9}
Original set2: {2, 3, 4}
Both sets are not equal
Explanation: The code compares two sets, a and b, using the equality operator (==). Since the sets have different elements (set a has elements {1, 2, 4, 5, 7, 8, 9} and set b has elements {2, 3, 4}), the condition evaluates to False and the statement “Both sets are not equal” is printed.

Python Set MCQ : Set 3

Python Set MCQ

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

List = [1, 2, 3, 4, 5]
list_set = set(List)
print(“Original list: “, List)
print(“List to set: “, list_set)

a) Original list: [1, 2, 3, 4, 5] List to set: {1, 2, 3, 4, 5}
b) Original list: {1, 2, 3, 4, 5} List to set: [1, 2, 3, 4, 5]
c) Original list: [1, 2, 3, 4, 5] List to set: [1, 2, 3, 4, 5]
d) Original list: {1, 2, 3, 4, 5} List to set: {1, 2, 3, 4, 5}

Correct answer is: a) Original list: [1, 2, 3, 4, 5] List to set: {1, 2, 3, 4, 5}
Explanation: The variable `List` is initialized with the values [1, 2, 3, 4, 5]. The set() function is used to convert the list into a set. The resulting set will contain unique elements from the list. The print statements display the original list and the set obtained from the list.

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

Set = {1, 2, 3, 4, 5}
set_list = list(Set)
print(“Original set: “, Set)
print(“set to list: “, set_list)

a) Original set: {1, 2, 3, 4, 5} set to list: [1, 2, 3, 4, 5]
b) Original set: {1, 2, 3, 4, 5} set to list: {1, 2, 3, 4, 5}
c) Original set: {1, 2, 3, 4, 5} set to list: (1, 2, 3, 4, 5)
d) Error: NameError: name ‘List’ is not defined

Correct answer is: a) Original set: {1, 2, 3, 4, 5} set to list: [1, 2, 3, 4, 5]
Explanation: The code initializes a set called “Set” with values 1, 2, 3, 4, and 5. It then converts the set into a list using the `list()` function and assigns it to the variable “set_list.” The first `print()` statement outputs the original set, which is {1, 2, 3, 4, 5}. The second `print()` statement outputs the converted list, which is [1, 2, 3, 4, 5].

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

Set = {10, 23, 45, 66, 96, 83}
print(“Original set1: “, Set)
maximum = 0
for ele in Set:
    if ele > maximum:
        maximum = ele
print(“Maximum value: “, maximum)

a) Original set1: {10, 23, 45, 66, 96, 83} Maximum value: 96
b) Original set1: {10, 23, 45, 66, 96, 83} Maximum value: 83
c) Original set1: {10, 23, 45, 66, 96, 83} Maximum value: 66
d) Original set1: {10, 23, 45, 66, 96, 83} Maximum value: 45

Correct answer is: a) Original set1: {10, 23, 45, 66, 96, 83} Maximum value: 96
Explanation: The code initializes a variable “maximum” to 0 and iterates through the elements of the set “Set”. It compares each element with the current maximum value and updates “maximum” if a larger element is found. The final value of “maximum” is the maximum value in the set, which is 96.

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

Set = {10, 23, 45, 66, 96, 83}
print(“Original set1: “, Set)
print(“Minimum value: “, min(Set))

a) Original set1: {10, 23, 45, 66, 96, 83}
Minimum value: 10
b) Original set1: {10, 23, 45, 66, 96, 83}
Minimum value: 96
c) Original set1: {10, 23, 45, 66, 96, 83}
Minimum value: 83
d) Error: min() function cannot be used on sets

Correct answer is: a) Original set1: {10, 23, 45, 66, 96, 83}
Minimum value: 10
Explanation: The code creates a set called “Set” with elements 10, 23, 45, 66, 96, and 83. It then prints the original set using the “print” statement. Finally, it uses the “min” function to find the minimum value in the set, which is 10.

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

Set = {1, 2, 3, 4, 5}
total = 0
print(“Original set1: “, Set)
for ele in Set:
    total += ele
print(“Total of elements in the set: “, total)

a) Original set1: {1, 2, 3, 4, 5}
Total of elements in the set: 15
b) Original set1: {1, 2, 3, 4, 5}
Total of elements in the set: 10
c) Original set1: {1, 2, 3, 4, 5}
Total of elements in the set: 14
d) Original set1: {1, 2, 3, 4, 5}
Total of elements in the set: 5

Correct answer is: a) Original set1: {1, 2, 3, 4, 5}
Total of elements in the set: 15
Explanation: The code initializes a set named “Set” with elements 1, 2, 3, 4, and 5. It also initializes a variable “total” as 0. The code then enters a loop where it iterates over each element “ele” in the set. Inside the loop, the value of “ele” is added to the “total” using the “+=” operator. After the loop, the code prints the original set and the total of elements in the set. In this case, the sum of elements in the set is 1 + 2 + 3 + 4 + 5 = 15. Therefore, the output is “Original set1: {1, 2, 3, 4, 5}” and “Total of elements in the set: 15.”

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

Set = {1, 2, 3, 4, 5}
print(“Original set1: “, Set)
total = 0
for ele in Set:
    total += ele
print(“Average of the set: “, total / len(Set))

a) Original set1: {1, 2, 3, 4, 5}
Average of the set: 3.0
b) Original set1: {1, 2, 3, 4, 5}
Average of the set: 3
c) Original set1: {1, 2, 3, 4, 5}
Average of the set: 15/5
d) Original set1: {1, 2, 3, 4, 5}
Average of the set: 2.5

Correct answer is: a) Original set1: {1, 2, 3, 4, 5}
Average of the set: 3.0
Explanation: The code calculates the sum of all elements in the set and divides it by the length of the set to find the average. The sum of 1 + 2 + 3 + 4 + 5 is 15, and the length of the set is 5, so the average is 15/5, which is 3.0. The output shows the original set and the calculated average.

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

Set = {1, 2, 3, 4, 5}
print(“Original set1: “, Set)
count = 0
for ele in Set:
    if ele % 2 == 0:
        count += 1
if count == len(Set):
    print(“All elements in the set are even”)
else:
    print(“All elements in the set are not even”)

a) All elements in the set are even
b) All elements in the set are not even
c) Original set1: {1, 2, 3, 4, 5}
d) Original set1: {2, 4}

Correct answer is: b) All elements in the set are not even
Explanation: The code initializes a set called “Set” with values {1, 2, 3, 4, 5}. It then iterates over each element in the set using a for loop. Inside the loop, it checks if the element is even (divisible by 2) using the condition `ele % 2 == 0`. If an even element is found, the `count` variable is incremented. After the loop, the code compares the value of `count` with the length of the set using the condition `count == len(Set)`. If the count is equal to the length, it means that all elements in the set are even. However, in this case, since the set contains both odd and even numbers, the condition `count == len(Set)` evaluates to False.

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

Set = {1, 2, 3, 4, 5}
print(“Original set1: “, Set)
count = 0
for ele in Set:
    if ele % 2 != 0:
        count += 1
if count == len(Set):
    print(“All elements in the set are odd”)
else:
    print(“All elements in the set are not odd”)

a) Original set1: {1, 2, 3, 4, 5} All elements in the set are not odd
b) Original set1: {1, 2, 3, 4, 5} All elements in the set are odd
c) Original set1: {1, 2, 3, 4, 5}
d) Error: Invalid syntax

Correct answer is: a) Original set1: {1, 2, 3, 4, 5} All elements in the set are not odd
Explanation: The code defines a set named “Set” with the values {1, 2, 3, 4, 5}. It then iterates over each element in the set using a for loop. If an element is not divisible by 2 (i.e., odd), the count variable is incremented. After iterating through all elements, the code checks if the count is equal to the length of the set. If they are equal, it means all elements are odd, and it prints “All elements in the set are odd.” Otherwise, it prints “All elements in the set are not odd.” 

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

Set = {1, 2, 3, 5}
prime = []

for ele in Set:
    count = 0
    for num in range(2, ele):
        if ele % num == 0:
            count += 1
    if count == 0:
        prime.append(ele)

if len(prime) == len(Set):
    print(“All elements in the set are prime numbers”)
else:
    print(“All elements in the set are not prime numbers”)

a) All elements in the set are prime numbers
b) All elements in the set are not prime numbers
c) The code will raise an error
d) The output cannot be determined

Correct answer is: a) All elements in the set are prime numbers
Explanation: The given code first initializes a set Set containing the elements {1, 2, 3, 5}. It also initializes an empty list prime. Next, the code iterates through each element ele in the set Set. For each element, it checks if there exists any number num between 2 and ele – 1 (exclusive) that divides ele without leaving a remainder. If such a number is found, the variable count is incremented. If the count remains 0 after the inner loop completes, it means the element is a prime number, and it is added to the prime list. After processing all elements in the set, the code checks if the number of prime elements in the prime list is equal to the total number of elements in the set Set. If they are equal, it means all elements in the set are prime numbers, and the corresponding message is printed. Otherwise, it means not all elements are prime numbers, and the appropriate message is printed.

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

a = {1, 2, 4, 5}
print(“Original set: “, a)
a.clear()
print(a)

a) Original set: {1, 2, 4, 5}
{}
b) Original set: {1, 2, 4, 5}
{1, 2, 4, 5}
c) Original set: {1, 2, 4, 5}
Error
d) Original set: {}
{}

Correct answer is: a) Original set: {1, 2, 4, 5}
{}
Explanation: The code defines a set `a` with elements [1, 2, 4, 5]. It then prints the original set `a`, which outputs `{1, 2, 4, 5}`. After that, the `clear()` method is called on set `a`, which removes all elements from the set. Finally, it prints the set `a` again, which results in an empty set `{}`.

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

a = {1, 2, 4, 5}
print(“Original set: “, a)
print(“Remove element from set: “, a.pop())
print(a)

a) Original set: {1, 2, 4, 5} Remove element from set: 1 {2, 4, 5}
b) Original set: {1, 2, 4, 5} Remove element from set: 5 {1, 2, 4}
c) Original set: {1, 2, 4, 5} Remove element from set: 2 {1, 4, 5}
d) Original set: {1, 2, 4, 5} Remove element from set: 4 {1, 2, 5}

Correct answer is: a) Original set: {1, 2, 4, 5} Remove element from set: 1 {2, 4, 5}
Explanation: The initial set “a” is defined as {1, 2, 4, 5}. When the pop() method is called on set “a”, it removes and returns an arbitrary element from the set. In this case, the element 1 is removed. Therefore, the output of “print(“Original set: “, a)” displays the original set as {1, 2, 4, 5}. The output of “print(“Remove element from set: “, a.pop())” displays the removed element, which is 1. 

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

a = {1, 2, 4, 5}
b = {2, 4}
print(“Original set1: “, a)
print(“Original set2: “, b)
print(“Difference between two sets using – operator: “, a – b)

a) Original set1: {1, 2, 4, 5}
Original set2: {2, 4}
Difference between two sets using – operator: {1, 5}
b) Original set1: {1, 2, 4, 5}
Original set2: {2, 4}
Difference between two sets using – operator: {1, 2, 4, 5}
c) Original set1: {1, 2, 4, 5}
Original set2: {2, 4}
Difference between two sets using – operator: {1, 4, 5}
d) Original set1: {1, 2, 4, 5}
Original set2: {2, 4}
Difference between two sets using – operator: {2, 4}

Correct answer is: a) Original set1: {1, 2, 4, 5}
Original set2: {2, 4}
Difference between two sets using – operator: {1, 5}
Explanation: The expression `a – b` represents the difference between set `a` and set `b`, which contains the elements present in set `a` but not in set `b`. In this case, the elements 1 and 5 are not present in set `b`, so they are included in the output set.

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

a = {1, 2, 4, 5}
b = {2, 4}
print(“Original set1: “, a)
print(“Original set2: “, b)
count = 0
for ele in b:
    if ele in a:
        count += 1
if count == len(b):
    print(“True”)
else:
    print(“False”)

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

Correct answer is: a) True
Explanation: The code compares the elements of set `b` with set `a`. If all elements of `b` are found in `a`, the variable `count` will be equal to the length of set `b`. In this case, since all elements of `b` (2 and 4) are present in `a`, the count will be equal to the length of `b` (2). Therefore, the output will be “True”.

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

Set = {10, 23, 45, 66, 96, 83}
print(“Original set1: “, Set)
print(“Maximum value: “, max(Set))

a) Original set1: {10, 23, 45, 66, 96, 83} Maximum value: 96
b) Original set1: {10, 23, 45, 66, 96, 83} Maximum value: 83
c) Original set1: {10, 23, 45, 66, 96, 83} Maximum value: 10
d) Original set1: {10, 23, 45, 66, 96, 83} Maximum value: 45

Correct answer is: a) Original set1: {10, 23, 45, 66, 96, 83} Maximum value: 96
Explanation: The given code defines a set named Set with elements 10, 23, 45, 66, 96, and 83. The print statement outputs the original set as {10, 23, 45, 66, 96, 83}. The max() function is used to find the maximum value from the set, which is 96. 

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

a = {1,2,4,5}
b = {2,4}
print(“Original set1: “,a)
print(“Original set2: “,b)
print(“Intersection between two sets using the “&” operator: “,a&b)

a) Original set1: {1, 2, 4, 5}
Original set2: {2, 4}
Intersection between two sets using the “&” operator: {2, 4}
b) Original set1: {1, 2, 4, 5}
Original set2: {2, 4}
Intersection between two sets using the “&” operator: {1, 2, 4, 5}
c) Original set1: {1, 2, 4, 5}
Original set2: {2, 4}
Intersection between two sets using the “&” operator: {1, 5}
d) Original set1: {1, 2, 4, 5}
Original set2: {2, 4}
Intersection between two sets using the “&” operator: {1, 2, 4, 5}

Correct answer is: a) Original set1: {1, 2, 4, 5}
Original set2: {2, 4}
Intersection between two sets using the “&” operator: {2, 4}
Explanation: The “&” operator is used to find the intersection between two sets. In this case, set “a” contains the elements {1, 2, 4, 5} and set “b” contains the elements {2, 4}. The intersection of these two sets is {2, 4}, which is displayed as the output.

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

a = {1, 2, 4, 5}
b = {7, 8}
c = {6, 10, 0}
print(“Original set1: “, a)
print(“Original set2: “, b)
print(“Original set3: “, c)
print(“Union of multiple sets using the | operator: “, a | b | c)

a) Original set1: {1, 2, 4, 5}
Original set2: {7, 8}
Original set3: {6, 10, 0}
Union of multiple sets using the | operator: {0, 1, 2, 4, 5, 6, 7, 8, 10}
b) Original set1: {1, 2, 4, 5}
Original set2: {7, 8}
Original set3: {6, 10, 0}
Union of multiple sets using the | operator: {1, 2, 4, 5, 7, 8, 6, 10, 0}
c) Original set1: {1, 2, 4, 5}
Original set2: {7, 8}
Original set3: {6, 10, 0}
Union of multiple sets using the | operator: {1, 2, 4, 5}
d) Error: Invalid use of the | operator for multiple sets

Correct answer is: b) Original set1: {1, 2, 4, 5}
Original set2: {7, 8}
Original set3: {6, 10, 0}
Union of multiple sets using the | operator: {1, 2, 4, 5, 7, 8, 6, 10, 0}
Explanation: The code initializes three sets: `a`, `b`, and `c`. Then it prints the original sets and performs the union operation using the `|` operator on all three sets. The resulting set contains all the elements from the three sets combined. In this case, the output will be `{1, 2, 4, 5, 7, 8, 6, 10, 0}`.

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

a = {1, 2, 4, 5}
b = {4, 1}
print(“Original set1: “, a)
print(“Original set2: “, b)
print(“Symmetric difference of two sets using the “^” operator: “, a^b)

a) Original set1: {1, 2, 4, 5}, Original set2: {4, 1}, Symmetric difference of two sets using the “^” operator: {2, 5}
b) Original set1: {1, 2, 4, 5}, Original set2: {4, 1}, Symmetric difference of two sets using the “^” operator: {1, 2, 4, 5}
c) Original set1: {1, 2, 4, 5}, Original set2: {4, 1}, Symmetric difference of two sets using the “^” operator: {1, 4}
d) Original set1: {1, 2, 4, 5}, Original set2: {4, 1}, Symmetric difference of two sets using the “^” operator: {1, 2, 4, 5}

Correct answer is: a) Original set1: {1, 2, 4, 5}, Original set2: {4, 1}, Symmetric difference of two sets using the “^” operator: {2, 5}
Explanation: The set a contains elements {1, 2, 4, 5} and set b contains elements {4, 1}. The “^” operator is used to calculate the symmetric difference between two sets, which is the set of elements that are present in either set but not in both. In this case, the symmetric difference of sets a and b is {2, 5}, which is printed as the output.

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

a = {1, 2, 4, 5}
b = {4, 1}
print(“Original set1: “, a)
print(“Original set2: “, b)
print(“A is superset of B: “, a.issuperset(b))

a) Original set1: {1, 2, 4, 5} Original set2: {4, 1} A is superset of B: True
b) Original set1: {1, 2, 4, 5} Original set2: {4, 1} A is superset of B: False
c) Original set1: {1, 2, 4, 5} Original set2: {1, 4} A is superset of B: True
d) Original set1: {4, 1} Original set2: {1, 4} A is superset of B: True

Correct answer is: a) Original set1: {1, 2, 4, 5} Original set2: {4, 1} A is superset of B: True
Explanation: The code initializes two sets, ‘a’ and ‘b’, with some elements. The ‘issuperset()’ method is then used to check if ‘a’ is a superset of ‘b’. In this case, ‘a’ contains all the elements of ‘b’ (1 and 4), making ‘a’ a superset of ‘b’. The output will be “Original set1: {1, 2, 4, 5} Original set2: {4, 1} A is superset of B: True”.

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

a = {1,2,4,5}
b = {4,1}
print(“Original set1: “,a)
print(“Original set2: “,b)
count = 0
for ele in b:
    if ele in a:
        count += 1
if count == len(b):
    print(“A is superset of B”)
else:
    print(“A is not a superset of B”)

a) A is superset of B
b) A is not a superset of B
c) Original set1: {1, 2, 4, 5} Original set2: {4, 1}
d) Original set1: {1, 2, 4, 5} Original set2: {4, 1} A is superset of B

Correct answer is: a) A is superset of B
Explanation: The code checks if set A is a superset of set B. In this case, set A contains all the elements of set B. Therefore, the output will be “A is superset of B.”

20). Which of the following output will be generated by the provided code?

a = {1,2,4,5}
b = {4,1}
print(“Original set1: “,a)
print(“Original set2: “,b)
print(“Common elements: “)
for ele in a:
    if ele in b:
        print(ele)

a) Original set1: {1, 2, 4, 5}
Original set2: {4, 1}
Common elements:
1
4
b) Original set1: {1, 2, 4, 5}
Original set2: {4, 1}
Common elements:
1
4
5
c) Original set1: {1, 2, 4, 5}
Original set2: {4, 1}
Common elements:
4
5
d) Original set1: {1, 2, 4, 5}
Original set2: {4, 1}
Common elements:
2
5

Correct answer is: a) Original set1: {1, 2, 4, 5}
Original set2: {4, 1}
Common elements:
1
4
Explanation: The provided code iterates over the elements in set `a` and checks if each element is present in set `b`. If an element is found in both sets, it is printed. In this case, the common elements between set `a` and `b` are 1 and 4.

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

a = {1, 2, 4, 5}
print(“Original set: “, a)
a.remove(5)
print(“After removing 5 from the given set: “, a)

a) Original set: {1, 2, 4, 5}
After removing 5 from the given set: {1, 2, 4}
b) Original set: {1, 2, 4, 5}
After removing 5 from the given set: {1, 2, 5}
c) Original set: {1, 2, 4, 5}
After removing 5 from the given set: {1, 2, 4, 5}
d) Original set: {1, 2, 4, 5}
After removing 5 from the given set: {1, 2, 4, 5, 6}

Correct answer is: a) Original set: {1, 2, 4, 5}
After removing 5 from the given set: {1, 2, 4}
Explanation: The original set `a` is defined as {1, 2, 4, 5}. When the `remove()` method is called with the argument 5, it removes the element 5 from the set. After removing 5, the set becomes {1, 2, 4}. Therefore, the output will be “Original set: {1, 2, 4, 5}” followed by “After removing 5 from the given set: {1, 2, 4}”.

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

a = {1, 2, 4, 5}
print(“Original set: “, a)
b = {7, 8, 9}
for ele in b:
    a.add(ele)
print(“New set: “, a)

a) Original set: {1, 2, 4, 5}
New set: {1, 2, 4, 5, 7, 8, 9}
b) Original set: {1, 2, 4, 5}
New set: {7, 8, 9}
c) Original set: {1, 2, 4, 5}
New set: {1, 2, 4, 5}
d) Original set: {7, 8, 9}
New set: {1, 2, 4, 5, 7, 8, 9}

Correct answer is: a) Original set: {1, 2, 4, 5} New set: {1, 2, 4, 5, 7, 8, 9}
Explanation: The original set `a` is initialized with elements 1, 2, 4, and 5. The set `b` is initialized with elements 7, 8, and 9. In the for loop, each element from set `b` is added to set `a` using the `add()` method. After the loop, the elements 7, 8, and 9 are added to set `a`.

Python Set MCQ : Set 2

Python Set MCQ

1). Which method is used to return the minimum element from a set?

a) min()
b) minimum()
c) smallest()
d) get_min()

Correct answer is: a) min()
Explanation: The min() function is used to return the minimum element from a set.

2). Which method is used to calculate the sum of elements in a set?

a) sum()
b) total()
c) calculate_sum()
d) get_sum()

Correct answer is: a) sum()
Explanation: The sum() function is used to calculate the sum of elements in a set.

3). Which method is used to find the union of multiple sets?

a) union()
b) combine()
c) merge()
d) unite()

Correct answer is: a) union()
Explanation: The union() method is used to find the union of multiple sets.

4). Which method is used to find the intersection of multiple sets?

a) intersection()
b) common()
c) intersect()
d) same()

Correct answer is: a) intersection()
Explanation: The intersection() method is used to find the intersection of multiple sets.

5). Which method is used to find the difference between multiple sets?

a) difference()
b) subtract()
c) diff()
d) minus()

Correct answer is: a) difference()
Explanation: The difference() method is used to find the difference between multiple sets.

6). Which method is used to find the symmetric difference between multiple sets?

a) symmetric_difference()
b) symmetric_diff()
c) symmetric()
d) diff_symmetric()

Correct answer is: a) symmetric_difference()
Explanation: The symmetric_difference() method is used to find the symmetric difference between multiple sets.

7). Which method is used to update a set with the union of itself and another set?

a) update()
b) add()
c) append()
d) merge()

Correct answer is: a) update()
Explanation: The update() method is used to update a set with the union of itself and another set.

8). Which method is used to remove an element from a set?

a) remove()
b) delete()
c) discard()
d) pop()

Correct answer is: a) remove()
Explanation: The remove() method is used to remove an element from a set.

9). Which method is used to remove an element from a set without raising an error if the element is not present?

a) remove()
b) delete()
c) discard()
d) pop()

Correct answer is: c) discard()
Explanation: The discard() method removes an element from a set, but if the element is not present, no error is raised.

10). Which method is used to check if two sets are disjoint (have no common elements)?

a) is_disjoint()
b) has_common()
c) check_disjoint()
d) is_empty()

Correct answer is: a) is_disjoint()
Explanation: The is_disjoint() method is used to check if two sets have no common elements.

11). Which method is used to check if a set is a superset of another set?

a) is_superset()
b) is_super()
c) superset()
d) issubset()

Correct answer is: a) is_superset()
Explanation: The is_superset() method is used to check if a set is a superset of another set.

12). Which method is used to check if two sets are equal?

a) is_equal()
b) equal()
c) equals()
d) == operator

Correct answer is: d) == operator
Explanation: The == operator is used to check if two sets are equal.

13). Which method is used to remove and return an arbitrary element from a set?

a) remove()
b) delete()
c) pop()
d) extract()

Correct answer is: c) pop()
Explanation: The pop() method removes and returns an arbitrary element from a set.

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

a = {1, 2, 3, 5, 6}
print(“Original set: “, a)
a.add(7)
print(“New set: “, a)

a) Original set: {1, 2, 3, 5, 6}, New set: {1, 2, 3, 5, 6}
b) Original set: {1, 2, 3, 5, 6}, New set: {1, 2, 3, 5, 6, 7}
c) Original set: {1, 2, 3, 5, 6}, New set: {7}
d) Original set: {1, 2, 3, 5, 6}, New set: {1, 2, 3, 5, 6, 7, 7}

Correct answer is: b) Original set: {1, 2, 3, 5, 6}, New set: {1, 2, 3, 5, 6, 7}
Explanation: The original set `a` contains the elements {1, 2, 3, 5, 6}. The `add()` method is used to add the element 7 to the set `a`. After adding 7, the new set becomes {1, 2, 3, 5, 6, 7}. Therefore, the output is “Original set: {1, 2, 3, 5, 6}, New set: {1, 2, 3, 5, 6, 7}”.

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

a = {1, 2, 3, 5, 6}
print(“Original set: “, a)
a.remove(5)
print(“New set: “, a)

a) Original set: {1, 2, 3, 5, 6}
New set: {1, 2, 3, 6}
b) Original set: {1, 2, 3, 5, 6}
New set: {1, 2, 3, 5, 6}
c) Original set: {1, 2, 3, 5, 6}
New set: {1, 2, 3}
d) Original set: {1, 2, 3, 5, 6}
New set: {1, 2, 3, 4, 6}

Correct answer is: a) Original set: {1, 2, 3, 5, 6}
New set: {1, 2, 3, 6}
Explanation: The original set `a` contains the elements 1, 2, 3, 5, and 6. The `remove(5)` method is used to remove the element 5 from the set. After removal, the new set `a` contains the elements 1, 2, and 3. Therefore, the output is “Original set: {1, 2, 3, 5, 6}” and “New set: {1, 2, 3, 6}”.

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

a = {1, 2, 3, 5, 6}
print(“Original set: “, a)
print(“Length of given set: “, len(a))

a) Original set: {1, 2, 3, 5, 6}; Length of given set: 5
b) Original set: {1, 2, 3, 5, 6}; Length of given set: 6
c) Original set: {1, 2, 3, 5, 6}; Length of given set: 4
d) Original set: {1, 2, 3, 5, 6}; Length of given set: 3

Correct answer is: a) Original set: {1, 2, 3, 5, 6}; Length of given set: 5
Explanation: The set `a` contains the elements 1, 2, 3, 5, and 6. When printing the original set, it will display as `{1, 2, 3, 5, 6}`. The `len(a)` function returns the length of the set, which is 5 in this case.

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

a = {1,2,3,5,6}
print(“Original set: “,a)
if 5 in a:
    print(“True”)
else:
    print(“False”)

a) Original set: {1, 2, 3, 5, 6}\nTrue
b) Original set: {1, 2, 3, 5, 6}\nFalse
c) Original set: {1, 2, 3, 5, 6}
d) True

Correct answer is: a) Original set: {1, 2, 3, 5, 6}\nTrue
Explanation: The code defines a set “a” with the elements {1, 2, 3, 5, 6}. The print statement displays the original set as “Original set: {1, 2, 3, 5, 6}”. The if statement checks if the number 5 is present in the set. Since 5 is indeed an element of the set, the code block under the if statement executes, which prints “True”. Hence, the output will be “Original set: {1, 2, 3, 5, 6}\nTrue” (where “\n” represents a new line).

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

a = {1, 2, 4, 5}
b = {7, 8, 9, 1}
print(“Original set1: “, a)
print(“Original set2: “, b)
print(“Union of a and b: “, a.union(b))

a) Original set1: {1, 2, 4, 5} Original set2: {7, 8, 9, 1} Union of a and b: {1, 2, 4, 5, 7, 8, 9}
b) Original set1: {1, 2, 4, 5} Original set2: {7, 8, 9, 1} Union of a and b: {1, 2, 4, 5}
c) Original set1: {1, 2, 4, 5} Original set2: {7, 8, 9, 1} Union of a and b: {7, 8, 9}
d) Original set1: {1, 2, 4, 5} Original set2: {7, 8, 9, 1} Union of a and b: {1, 7, 2, 4, 5, 8, 9}

Correct answer is: a) Original set1: {1, 2, 4, 5} Original set2: {7, 8, 9, 1} Union of a and b: {1, 2, 4, 5, 7, 8, 9}
Explanation: The code creates two sets, `a` and `b`, with specific elements. The `union()` method is then called on set `a` with `b` as an argument. The `union()` method returns a new set that contains all unique elements from both sets. In this case, the union of `a` and `b` will be {1, 2, 4, 5, 7, 8, 9}, which will be printed as the output.

20). What is the output of the code?

a = {1,2,4,5}
b = {7,8,9,1}
print(“Original set1: “,a)
print(“Original set2: “,b)
print(“Intersection of a and b: “,a.intersection(b))

a) Original set1: {1, 2, 4, 5} Original set2: {7, 8, 9, 1} Intersection of a and b: {1}
b) Original set1: {1, 2, 4, 5} Original set2: {7, 8, 9, 1} Intersection of a and b: {1, 7, 8, 9}
c) Original set1: {1, 2, 4, 5} Original set2: {7, 8, 9, 1} Intersection of a and b: {2, 4, 5}
d) Original set1: {1, 2, 4, 5} Original set2: {7, 8, 9, 1} Intersection of a and b: {7, 8, 9}

Correct answer is: a) Original set1: {1, 2, 4, 5} Original set2: {7, 8, 9, 1} Intersection of a and b: {1}
Explanation: The intersection of sets a and b is the set of elements that are common to both sets. In this case, the intersection is {1}, as 1 is present in both sets a and b. The intersection() method is used to find the intersection of sets. The code correctly prints the original sets and the intersection set.

21). What is the output of the above code?

a = {1,2,4,5}
b = {7,8,9,1}
print(“Original set1: “,a)
print(“Original set2: “,b)
print(“Difference of a and b: “,a.difference(b))

a) Original set1: {1, 2, 4, 5}
Original set2: {7, 8, 9, 1}
Difference of a and b: {2, 4, 5}
b) Original set1: {1, 2, 4, 5}
Original set2: {7, 8, 9, 1}
Difference of a and b: {1, 2, 4, 5}
c) Original set1: {1, 2, 4, 5}
Original set2: {7, 8, 9, 1}
Difference of a and b: {2, 4, 5}
d) Original set1: {1, 2, 4, 5}
Original set2: {7, 8, 9, 1}
Difference of a and b: {}

Correct answer is: c) Original set1: {1, 2, 4, 5}
Original set2: {7, 8, 9, 1}
Difference of a and b: {2, 4, 5}
Explanation: The difference() method returns a new set containing the elements that are present in set ‘a’ but not in set ‘b’.

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

a = {1,2,4,5}
b = {7,8,9,1}
print(“Original set1: “,a)
print(“Original set2: “,b)
print(“Symmetric difference of a and b: “,a.symmetric_difference(b))

a) Original set1: {1, 2, 4, 5} Original set2: {7, 8, 9, 1} Symmetric difference of a and b: {2, 4, 5, 7, 8, 9}
b) Original set1: {1, 2, 4, 5} Original set2: {7, 8, 9, 1} Symmetric difference of a and b: {2, 4, 5}
c) Original set1: {1, 2, 4, 5} Original set2: {7, 8, 9, 1} Symmetric difference of a and b: {1, 7, 8, 9}
d) Original set1: {1, 2, 4, 5} Original set2: {7, 8, 9, 1} Symmetric difference of a and b: {1}

Correct answer is: a) Original set1: {1, 2, 4, 5} Original set2: {7, 8, 9, 1} Symmetric difference of a and b: {2, 4, 5, 7, 8, 9}
Explanation: The symmetric_difference() method returns a new set that contains elements present in either set a or set b, but not in both.

Python Set MCQ : Set 1

Python Set MCQ

1). What is a set in Python?

a) A sequence of elements
b) A collection of unordered and unique elements
c) A data structure used for sorting elements
d) A variable that can store multiple values

Correct answer is: b) A collection of unordered and unique elements
Explanation: In Python, a set is an unordered collection of unique elements.

2). Which symbol is used to define a set in Python?

a) []
b) {}
c) ()
d) <>

Correct answer is: b) {}
Explanation: Curly braces {} are used to define a set in Python.

3). What is the result of executing the following code: set = {1, 2, 3}?

a) [1, 2, 3, 4]
b) {1, 2, 3,}
c) {1, 2, 3}
d) {2, 2, 3, 1}

Correct answer is: c) {1, 2, 3}
Explanation: Sets only contain unique elements, so duplicate values are removed.

4). In Python which method is used to add an element to a set?

a) add()
b) insert()
c) append()
d) update()

Correct answer is: a) add()
Explanation: The add() method is used to add a single element to a set.

5). Which method is used to remove an element from a set?

a) remove()
b) delete()
c) discard()
d) pop()

Correct answer is: c) discard()
Explanation: The discard() method removes a specified element from a set.

6). What happens if you use the remove() method to remove an element that doesn’t exist in the set?

a) It raises a KeyError
b) It raises an IndexError
c) It removes the last element in the set
d) It does nothing and doesn’t raise an error

Correct answer is: a) It raises a KeyError
Explanation: The remove() method raises a KeyError if the element doesn’t exist in the set.

7). Which method is used to remove an arbitrary element from a set?

a) remove()
b) delete()
c) discard()
d) pop()

Correct answer is: d) pop()
Explanation: The pop() method removes and returns an arbitrary element from a set.

8). Which method is used to clear all elements from a set?

a) clear()
b) remove()
c) discard()
d) delete()

Correct answer is: a) clear()
Explanation: The clear() method removes all elements from a set, leaving an empty set.

9). Which operator is used to perform the union of two sets?

a) &
b) |
c) –
d) ^

Correct answer is: b) |
Explanation: The | operator is used for the union operation, which combines elements from two sets.

10). Which operator is used to perform the intersection of two sets?

a) &
b) |
c) –
d) ^

Correct answer is: a) &
Explanation: The & operator is used for the intersection operation, which returns common elements from two sets.

11). Which operator is used to perform the difference between two sets?

a) &
b) |
c) –
d) ^

Correct answer is: c) –
Explanation: The – operator is used for the difference operation, which returns elements present in the first set but not in the second set.

12). Which operator is used to perform the symmetric difference between two sets?

a) &
b) |
c) –
d) ^

Correct answer is: d) ^
Explanation: The ^ operator is used for the symmetric difference operation, which returns elements present in either set, but not in both.

13). What is the result of executing the following code: set1 = {1, 2, 3}; set2 = {3, 4, 5}; symmetric_difference_set = set1 ^ set2; print(symmetric_difference_set)?
a) {1, 2, 3, 4, 5}
b) []
c) {1, 2, 4, 5}
d) {1, 2, 3}

Correct answer is: c) {1, 2, 4, 5}
Explanation: The ^ operator returns elements present in either set but not in both, which are 1, 2, 4, and 5.

14). Which method is used to check if a set is a subset of another set?

a) issubset()
b) issuperset()
c) subset()
d) superset()

Correct answer is: a) issubset()
Explanation: The issubset() method checks if a set is a subset of another set.

15). Which method is used to check if a set is a superset of another set?

a) issubset()
b) issuperset()
c) subset()
d) superset()

Correct answer is: b) issuperset()
Explanation: The issuperset() method checks if a set is a superset of another set.

16). Which method is used to check if two sets have no common elements?

a) isdisjoint()
b) iscommon()
c) nocommon()
d) nodisjoint()

Correct answer is: a) isdisjoint()
Explanation: The isdisjoint() method checks if two sets have no common elements.

17). Which method is used to return a shallow copy of a set?

a) copy()
b) clone()
c) duplicate()
d) replicate()

Correct answer is: a) copy()
Explanation: The copy() method in Python returns a shallow copy of a set.

18). Which method is used to return the length of a set?

a) size()
b) length()
c) count()
d) len()

Correct answer is: d) len()
Explanation: The len() function in Python returns the number of elements in a set.

19). Which method is used to convert a list into a set?

a) to_set()
b) set()
c) convert_set()
d) list_to_set()

Correct answer is: b) set()
Explanation: The set() function is used to convert a list into a set.

20). Which method is used to convert a set into a list?

a) to_list()
b) list()
c) convert_list()
d) set_to_list()

Correct answer is: b) list()
Explanation: The list() function is used to convert a set into a list.

21). Which method is used to iterate over the elements of a set?

a) iterate()
b) for loop
c) loop()
d) iterate_elements()

Correct answer is: b) for loop
Explanation: A for loop is used to iterate over the elements of a set.

22). Which method is used to return a frozen set from a set?

a) freeze()
b) frozen_set()
c) freeze_set()
d) frozenset()

Correct answer is: d) frozenset()
Explanation: The frozenset() function is used to return a frozen set from a set.

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. 

Python Dictionary MCQ : Set 3

Python Dictionary MCQ

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

dict1 = {‘course’:’python’,’institute’:’sqatools’ }
dict2 = {‘name’:’omkar’}

dict2.update(dict1)
print(dict2)

a) {‘name’: ‘omkar’}
b) {‘name’: ‘omkar’, ‘course’: ‘python’, ‘institute’: ‘sqatools’}
c) {‘course’: ‘python’, ‘institute’: ‘sqatools’}
d) {‘course’: ‘python’, ‘institute’: ‘sqatools’, ‘name’: ‘omkar’}

Corresct answer is: d) {‘course’: ‘python’, ‘institute’: ‘sqatools’, ‘name’: ‘omkar’}
Explanation: The `update()` method merges the key-value pairs from `dict1` into `dict2`. Since `dict2` is being updated with the key-value pairs from `dict1`, the resulting dictionary will have all the key-value pairs from both dictionaries. Therefore, the output will be `{‘course’: ‘python’, ‘institute’: ‘sqatools’, ‘name’: ‘omkar’}`.

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

dict1 = {}

for i in range(1, 6):
    dict1[i] = i ** 2

print(dict1)

a) {1: 1, 2: 4, 3: 9, 4: 16, 5: 25}
b) {1: 1, 4: 8, 9: 27, 16: 64, 25: 125}
c) {1: 1, 2: 2, 3: 3, 4: 4, 5: 5}
d) {1: 2, 4: 8, 9: 18, 16: 32, 25: 50}

Corresct answer is: a) {1: 1, 2: 4, 3: 9, 4: 16, 5: 25}
Explanation: The code initializes an empty dictionary `dict1` and then uses a for loop to iterate through the numbers 1 to 5. For each number, it assigns the square of the number as the value to the corresponding key in the dictionary. Therefore, the final dictionary will be {1: 1, 2: 4, 3: 9, 4: 16, 5: 25}.

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

dict1 = {‘a’: 2, ‘b’: 4, ‘c’: 5}
result = 1

for val in dict1.values():
    result *= val

print(result)

a) 8
b) 20
c) 40
d) 60

Corresct answer is: c) 40
Explanation: The code initializes `result` as 1 and then iterates over the values in `dict1`. It multiplies each value with `result` using the `*=` operator. Therefore, the result is the product of all the values: `2 * 4 * 5 = 40`.

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

dict1 = {‘a’: 2, ‘b’: 4, ‘c’: 5}

if ‘c’ in dict1:
    del dict1[‘c’]
print(dict1)

a) {‘a’: 2, ‘b’: 4}
b) {‘a’: 2, ‘b’: 4, ‘c’: 5}
c) {‘a’: 2, ‘b’: 4, ‘c’: None}
d) Error

Corresct answer is: a) {‘a’: 2, ‘b’: 4}
Explanation: The code checks if the key ‘c’ is present in the dictionary using the `in` keyword. Since ‘c’ exists as a key in dict1, the block of code inside the `if` statement is executed. The `del` statement removes the key-value pair with the key ‘c’ from the dictionary. Therefore, the resulting dictionary is {‘a’: 2, ‘b’: 4}.

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

list1 = [‘name’, ‘sport’, ‘rank’, ‘age’]
list2 = [‘Virat’, ‘cricket’, 1, 32]

new_dict = dict(zip(list1, list2))
print(new_dict)

a) {‘name’: ‘Virat’, ‘sport’: ‘cricket’, ‘rank’: 1, ‘age’: 32}
b) {‘Virat’: ‘name’, ‘cricket’: ‘sport’, 1: ‘rank’, 32: ‘age’}
c) {‘name’: ‘Virat’, ‘sport’: ‘cricket’}
d) Error

Corresct answer is: a) {‘name’: ‘Virat’, ‘sport’: ‘cricket’, ‘rank’: 1, ‘age’: 32}
Explanation: The code creates a new dictionary by combining the elements of `list1` as keys and `list2` as values using the `zip()` function. The resulting dictionary has the key-value pairs {‘name’: ‘Virat’, ‘sport’: ‘cricket’, ‘rank’: 1, ‘age’: 32}.

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

dict1 = {‘a’: 10, ‘b’: 44, ‘c’: 60, ‘d’: 25}
list1 = []

for val in dict1.values():
    list1.append(val)

list1.sort()
print(“Minimum value: “, list1[0])
print(“Maximum value: “, list1[-1])

a) Minimum value: 10, Maximum value: 60
b) Minimum value: 25, Maximum value: 60
c) Minimum value: 10, Maximum value: 44
d) Minimum value: 25, Maximum value: 44

Corresct answer is: a) Minimum value: 10, Maximum value: 60
Explanation: The code creates a list, `list1`, and appends all the values from `dict1` to it. The list is then sorted in ascending order using the `sort()` method. The first element of the sorted list (`list1[0]`) is the minimum value, which is 10. The last element of the sorted list (`list1[-1]`) is the maximum value, which is 60. Therefore, the output will be “Minimum value: 10, Maximum value: 60”.

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

from collections import defaultdict
list1 = [1, 3, 4, 4, 2, 5, 3, 1, 5, 5, 2]
print(“The original list: “, list1)

dict1 = defaultdict(list)
for val in list1:
    dict1[val].append(val)
print(“Similar grouped dictionary: “, dict1)

a) The original list: [1, 3, 4, 4, 2, 5, 3, 1, 5, 5, 2]
Similar grouped dictionary: {1: [1, 1], 3: [3, 3], 4: [4, 4], 2: [2, 2], 5: [5, 5, 5, 5]}
b) The original list: [1, 3, 4, 4, 2, 5, 3, 1, 5, 5, 2]
Similar grouped dictionary: {1: [1, 1], 3: [3, 3], 4: [4, 4], 2: [2, 2], 5: [5, 5]}
c) The original list: [1, 3, 4, 4, 2, 5, 3, 1, 5, 5, 2]
Similar grouped dictionary: {1: [1, 1], 3: [3, 3], 4: [4, 4], 2: [2, 2], 5: [5, 5, 5]}
d) The original list: [1, 3, 4, 4, 2, 5, 3, 1, 5, 5, 2]
Similar grouped dictionary: {1: [1, 1], 3: [3, 3], 4: [4, 4], 2: [2, 2], 5: [5, 5, 5]}

Corresct answer is: c) The original list: [1, 3, 4, 4, 2, 5, 3, 1, 5, 5, 2]
Similar grouped dictionary: {1: [1, 1], 3: [3, 3], 4: [4, 4], 2: [2, 2], 5: [5, 5, 5]}
Explanation: The code uses the `defaultdict` class from the `collections` module. A `defaultdict` is a subclass of a dictionary that provides a default value for a nonexistent key. In this code, the default value is an empty list.The code then creates an empty `defaultdict` called `dict1`. It iterates over each value in `list1`. For each value, it appends the value itself to the corresponding key in the dictionary. This results in grouping similar values together.The resulting similar grouped dictionary is printed as: {1: [1, 1], 3: [3, 3], 4: [4, 4], 2: [2, 2], 5: [5, 5, 5]}

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

string = ‘learning python at sqa-tools’
Dict = {‘at’: ‘is’, ‘sqa-tools’: ‘fun’}

for key, value in Dict.items():
    string = string.replace(key, value)
print(string)

a) ‘learning python is fun’
b) ‘learning python at sqa-tools’
c) ‘learning python at fun’
d) ‘learning python is sqa-tools’

Corresct answer is: a) ‘learning python is fun’
Explanation: The code iterates over the key-value pairs in the dictionary `Dict`. For each key-value pair, it replaces all occurrences of the key in the `string` with the corresponding value using the `replace()` method. In the first iteration, ‘at’ is replaced with ‘is’, resulting in the string: ‘learning python is sqa-tools’. In the second iteration, ‘sqa-tools’ is replaced with ‘fun’, resulting in the final string: ‘learning python is fun’. The modified `string` is printed, which outputs ‘learning python is fun’.

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

String = ‘sqatools is best for learning python’
Dict = {‘best’:2,’learning’:6}

str2 = “”
for word in String.split(” “):
    if word not in Dict:
        str2 += word + ” “
print(str2)

a) ‘sqatools is best for learning python’
b) ‘sqatools is for python’
c) ‘is for python’
d) ‘sqatools is best for’

Corresct answer is: b) ‘sqatools is for python’
Explanation: The code iterates over each word in the `String` variable, splitting it by spaces. It checks if each word is present in the `Dict` dictionary. If a word is not found in the dictionary, it is appended to the `str2` variable followed by a space. In this case, the words ‘best’ and ‘learning’ are present in the dictionary, so they are not included in `str2`. Hence, the output is ‘sqatools is for python’.

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

dict1 = {}

if len(dict1) > 0:
    print(“Dictionary is not empty”)
else:
    print(“Dictionary is empty”

a) “Dictionary is not empty”
b) “Dictionary is empty”
c) Error
d) None

Corresct answer is: b) “Dictionary is empty”
Explanation: The code initializes an empty dictionary `dict1`. The `len(dict1)` function returns the number of key-value pairs in the dictionary, which is 0 in this case. Since the condition `len(dict1) > 0` is not satisfied, the code enters the `else` block and prints “Dictionary is empty”.

11). What will be the output of the following code snippet?

Dict1 = {‘x’:10,’y’:20,’c’:50,’f’:44 }
Dict2 = {‘x’:60,’c’:25,’y’:56}

for key in Dict1:
    for k in Dict2:
        if key == k:
            a = Dict1[key]+Dict2[k]
            Dict2[key] = a
print(Dict2)

a) {‘x’: 70, ‘c’: 75, ‘y’: 76}
b) {‘x’: 60, ‘c’: 25, ‘y’: 56}
c) {‘x’: 10, ‘y’: 20, ‘c’: 50, ‘f’: 44}
d) {‘x’: 10, ‘y’: 20, ‘c’: 50, ‘f’: 44, ‘y’: 76}

Corresct answer is: a) {‘x’: 70, ‘c’: 75, ‘y’: 76}
Explanation: The code iterates through each key in Dict1 and checks if it exists as a key in Dict2. If a matching key is found, the corresponding values from Dict1 and Dict2 are added together and stored in variable ‘a’. Then, the key-value pair in Dict2 is updated with the new value ‘a’. Finally, the updated Dict2 is printed, which will be {‘x’: 70, ‘c’: 75, ‘y’: 76}. The value for key ‘x’ is 10 + 60 = 70, the value for key ‘c’ is 50 + 25 = 75, and the value for key ‘y’ is 20 + 56 = 76. The key ‘f’ from Dict1 is not present in Dict2, so it remains unchanged in the final result.

12). What is the output of the following Python code?


list1 = [{‘name1′:’robert’},{‘name2′:’john’},{‘name3′:’jim’}, {‘name4′:’robert’}]
list2 = []
for val in list1:
    for ele in val.values():
        if ele not in list2:
            list2.append(ele)
print(list2)

a) [‘robert’, ‘john’, ‘jim’]
b) [‘robert’, ‘john’, ‘jim’, ‘robert’]
c) [‘john’, ‘jim’]
d) [‘robert’]

Corresct answer is: a) [‘robert’, ‘john’, ‘jim’]
Explanation: The code iterates over each dictionary in `list1` using the variable `val`. Then, within each dictionary, it retrieves the value using the `values()` method. The retrieved value is checked if it already exists in `list2`. If not, it is appended to `list2`. Since the value ‘robert’ appears twice in `list1`, it is added twice to `list2`. Therefore, the output will be `[‘robert’, ‘john’, ‘jim’]`.

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

import pandas as pd
dict1 = {‘names’:[‘virat’,’messi’,’kobe’],’sport’:[‘cricket’,’football’,’basketball’]}

table = pd.DataFrame(dict1)
print(table)

a)

| | names | sport |
|—|——-|————|
| 0 | virat | cricket |
| 1 | messi | football |
| 2 | kobe | basketball |

b)

| | names | sport |
|—|——-|————|
| 0 | virat | football |
| 1 | messi | cricket |
| 2 | kobe | basketball |

c)

| | names | sport |
|—|——-|————|
| 0 | virat | basketball |
| 1 | messi | cricket |
| 2 | kobe | football |

d)

| | names | sport |
|—|——-|————|
| 0 | virat | cricket |
| 1 | kobe | basketball |
| 2 | messi | football |

Corresct answer is: a)

| | names | sport |
|—|——-|————|
| 0 | virat | cricket |
| 1 | messi | football |
| 2 | kobe | basketball |

Explanation: The code creates a dictionary called `dict1` with two keys: ‘names’ and ‘sport’, and their corresponding values as lists. It then creates a DataFrame using `pd.DataFrame()` by passing the dictionary as an argument. The DataFrame is displayed using `print(table)`. The resulting table has three rows, where each row represents a player’s name and their associated sport.

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

list1 = [2, 5, 8, 1, 2, 6, 8, 5, 2]
dict1 = {}

for val in list1:
    dict1[val] = list1.count(val)
print(dict1)

a) {1: 1, 2: 3, 5: 2, 6: 1, 8: 2}
b) {2: 3, 5: 2, 8: 2, 1: 1, 6: 1}
c) {2: 3, 5: 2, 8: 2, 1: 1, 6: 1, 0: 0}
d) {2: 3, 5: 2, 8: 2, 1: 1, 6: 1, 9: 0}

Corresct answer is: a) {1: 1, 2: 3, 5: 2, 6: 1, 8: 2}
Explanation: The code creates an empty dictionary `dict1` and then iterates over each value in `list1`. For each value, it counts the number of occurrences using `list1.count(val)` and assigns that count as the value in the dictionary with the value itself as the key. The resulting dictionary will contain the counts of each unique value from the list.In this case, the output dictionary will be `{1: 1, 2: 3, 5: 2, 6: 1, 8: 2}`. Value 1 appears once, value 2 appears three times, value 5 appears twice, value 6 appears once, and value 8 appears twice.

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

dict1 = {‘m1’: 25, ‘m2’: 20, ‘m3’: 15}
total = 0
count = 0

for val in dict1.values():
    total += val
    count += 1
print(“Mean: “, (total / count))

a) Mean: 25
b) Mean: 20
c) Mean: 15
d) Mean: 20.0

Corresct answer is: d) Mean: 20.0
Explanation: The code calculates the mean of the values in the dict1 dictionary. It iterates over the values using a loop, calculates the total sum of the values, and increments the count. Finally, it prints the mean by dividing the total by the count. In this case, the mean is 20.0.

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

list1 = [‘a’, ‘b’, ‘c’, ‘d’]
new_dict = current = {}

for char in list1:
    current[char] = {}
    current = current[char]
print(new_dict)

a) {‘a’: {‘b’: {‘c’: {‘d’: {}}}}}
b) {‘d’: {‘c’: {‘b’: {‘a’: {}}}}}
c) {‘a’: {}, ‘b’: {}, ‘c’: {}, ‘d’: {}}
d) {‘d’: {}, ‘c’: {}, ‘b’: {}, ‘a’: {}}

Corresct answer is: a) {‘a’: {‘b’: {‘c’: {‘d’: {}}}}}
Explanation: The given code iterates over each character in the list list1. It creates nested dictionaries where each character becomes a key for the next nested dictionary.

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

dict1 = {‘a1’: [1, 5, 3], ‘a2’: [10, 6, 20]}
for val in dict1.values():
    val.sort()
print(dict1)

a) {‘a1’: [1, 3, 5], ‘a2’: [6, 10, 20]}
b) {‘a1’: [1, 5, 3], ‘a2’: [10, 6, 20]}
c) {‘a1’: [1, 5, 3], ‘a2’: [6, 10, 20]}
d) {‘a1’: [1, 3, 5], ‘a2’: [10, 20, 6]}

Corresct answer is: a) {‘a1’: [1, 3, 5], ‘a2’: [6, 10, 20]}
Explanation: The code iterates over the values in `dict1` using a for loop. Each value, which is a list, is sorted in ascending order using the `sort()` method. After the loop, the dictionary `dict1` is printed. Since lists are mutable objects, sorting the values in-place affects the original dictionary. Therefore, the output will be `{‘a1’: [1, 3, 5], ‘a2’: [6, 10, 20]}` with the values sorted in ascending order within each list.

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

dict1 = {‘virat’:{‘sport’:’cricket’,’team’:’india’},
‘messi’:{‘sport’:’football’,’team’:’argentina’}}
for key, val in dict1.items():
    print(key)
    for k,v in val.items():
        print(k,”:”,v)

a) virat
sport: cricket
team: india
messi
sport: football
team: argentina
b) virat
sport: cricket
messi
sport: football
team: argentina
c) virat: sport: cricket, team: india
messi: sport: football, team: argentina
d) sport: cricket, team: india
sport: football, team: argentina

Corresct answer is: a) virat
sport: cricket
team: india
messi
sport: football
team: argentina
Explanation: The code iterates over the items of the `dict1` dictionary. For each key-value pair, it prints the key and then iterates over the nested dictionary `val`. For each key-value pair in `val`, it prints the key and value. Therefore, the output includes the keys ‘virat’ and ‘messi’, followed by their respective key-value pairs from the nested dictionaries.

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

dict1 = {‘sqa’:[1,4,6],’tools’:[3,6,9]}
list1 = []

for key,val in dict1.items():
    l = []
    l.append(key)
    for ele in val:
        l.append(ele)
    list1.append(list(l))
print(list1)

a) [[‘sqa’, 1, 4, 6], [‘tools’, 3, 6, 9]]
b) [[‘sqa’, [1, 4, 6]], [‘tools’, [3, 6, 9]]]
c) [[‘sqa’, 1], [‘sqa’, 4], [‘sqa’, 6], [‘tools’, 3], [‘tools’, 6], [‘tools’, 9]]
d) [[‘sqa’, [1, 4, 6]], [‘tools’, [3, 6, 9]], [‘sqa’, [1, 4, 6]], [‘tools’, [3, 6, 9]]]

Corresct answer is: a) [[‘sqa’, 1, 4, 6], [‘tools’, 3, 6, 9]]
Explanation: The code iterates over the key-value pairs in the dictionary. For each pair, it creates a new list and appends the key followed by the values from the corresponding list. These lists are then appended to the list1. The final output is [[‘sqa’, 1, 4, 6], [‘tools’, 3, 6, 9]].

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

dict1 = [{‘sqa’: 123, ‘tools’: 456}]
l = []
for ele in dict1:
    for k in ele.keys():
        a = []
        a.append(k)
        l.append(a)
    for v in ele.values():
        b = []
        b.append(v)
        l.append(b)
print(l)

a) [[‘sqa’], [123], [‘tools’], [456]]
b) [{‘sqa’}, {123}, {‘tools’}, {456}]
c) [[‘sqa’, ‘tools’], [123, 456]]
d) [[{‘sqa’: 123, ‘tools’: 456}]]

Corresct answer is: a) [[‘sqa’], [123], [‘tools’], [456]]
Explanation: The code iterates over the list `dict1` which contains a single dictionary element. For each dictionary element, it retrieves the keys using `ele.keys()` and appends them as separate lists to `l`. Then it retrieves the values using `ele.values()` and appends them as separate lists to `l`. Finally, it prints the resulting list `l`, which contains individual lists for each key and value. Therefore, the output will be `[[‘sqa’], [123], [‘tools’], [456]]`.

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

dict1 = {‘virat’: [‘match1’, ‘match2’, ‘match3’], ‘rohit’: [‘match1’, ‘match2’]}
count = 0

for val in dict1.values():
    for ele in val:
        count += 1
print(“Items in the list of values: “, count)

a) 3
b) 5
c) 6
d) 8

Corresct answer is: b) 5
Explanation: The code snippet iterates over the values of the dictionary `dict1`. For each value, it iterates over the elements using a nested loop. In this case, the values are `[‘match1’, ‘match2’, ‘match3’]` and `[‘match1’, ‘match2’]`. So, the total count of items in the list of values is 5.

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

dict1 = {‘Math’:70,’Physics’:90,’Chemistry’:67}
a = sorted(dict1.items(), key = lambda val:val[1], reverse = True)
print(a)

a) [(‘Physics’, 90), (‘Math’, 70), (‘Chemistry’, 67)]
b) [(‘Math’, 70), (‘Physics’, 90), (‘Chemistry’, 67)]
c) [(‘Chemistry’, 67), (‘Math’, 70), (‘Physics’, 90)]
d) [(‘Physics’, 90), (‘Chemistry’, 67), (‘Math’, 70)]

Corresct answer is: a) [(‘Physics’, 90), (‘Math’, 70), (‘Chemistry’, 67)]
Explanation: The code sorts the dictionary items based on the values in descending order. The sorted() function is called with the key argument set to a lambda function that returns the value of each item. The reverse parameter is set to True to sort in descending order. The output is a list of tuples, where each tuple contains a key-value pair from the original dictionary, sorted by the values in descending order.

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

dict1 = [{‘name’: ‘ketan’, ‘subject’: ‘maths’, ‘p1’: 80, ‘p2’: 70}]
for d in dict1:
n1 = d.pop(‘p1’)
n2 = d.pop(‘p2’)
d[‘p1+p2’] = (n1 + n2) / 2

print(dict1)

a) [{‘name’: ‘ketan’, ‘subject’: ‘maths’, ‘p1+p2’: 150}]
b) [{‘name’: ‘ketan’, ‘subject’: ‘maths’, ‘p1+p2’: 75}]
c) [{‘name’: ‘ketan’, ‘subject’: ‘maths’, ‘p1’: 80, ‘p2’: 70, ‘p1+p2’: 75}]
d) Error

Corresct answer is: b) [{‘name’: ‘ketan’, ‘subject’: ‘maths’, ‘p1+p2’: 75}]
Explanation: The code iterates over the list of dictionaries. For each dictionary, it removes the ‘p1’ and ‘p2’ keys and calculates their average. Then, it adds a new key ‘p1+p2’ with the calculated average value. Finally, it prints the modified list of dictionaries. In this case, the output will be [{‘name’: ‘ketan’, ‘subject’: ‘maths’, ‘p1+p2’: 75}] because the average of 80 and 70 is 75.

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

dict1 = {‘k1′:’p’,’k2′:’q’,’k3′:’r’}
dict2 = {‘k1′:’p’,’k2′:’s’}

for key in dict1:
    if key in dict2:
        print(f”{key} is present in both dictionaries”)
    else:
        print(f”{key} is present not in both dictionaries”)

a) k1 is present in both dictionaries
k2 is present not in both dictionaries
k3 is present not in both dictionaries
b) k1 is present in both dictionaries
k2 is present in both dictionaries
k3 is present not in both dictionaries
c) k1 is present in both dictionaries
k2 is present in both dictionaries
k3 is present in both dictionaries
d) k1 is present in both dictionaries
k2 is present not in both dictionaries
k3 is present in both dictionaries

Corresct answer is: b) k1 is present in both dictionaries
k2 is present in both dictionaries
k3 is present not in both dictionaries
Explanation: The given code iterates over the keys of `dict1`. It checks if each key is present in `dict2`. If a key is found in both dictionaries, it prints that the key is present in both dictionaries. If a key is only present in `dict1`, it prints that the key is not present in both dictionaries. In this case, ‘k1’ is present in both dictionaries, ‘k2’ is present in both dictionaries, and ‘k3’ is present only in `dict1`.

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

l1 = []
for i in range(1, 6):
    l1.append(i)

l2 = []
for i in range(6, 11):
    l2.append(i)

l3 = []
for i in range(11, 16):
    l3.append(i)

dict1 = {}
dict1[“a”] = l1
dict1[“b”] = l2
dict1[“c”] = l3
print(dict1)

a) {‘a’: [1, 2, 3, 4, 5], ‘b’: [6, 7, 8, 9, 10], ‘c’: [11, 12, 13, 14, 15]}
b) {‘a’: [1, 2, 3, 4, 5], ‘b’: [1, 2, 3, 4, 5], ‘c’: [1, 2, 3, 4, 5]}
c) {‘a’: [1, 2, 3, 4], ‘b’: [6, 7, 8, 9], ‘c’: [11, 12, 13, 14]}
d) {‘a’: [1, 2, 3, 4], ‘b’: [5, 6, 7, 8], ‘c’: [9, 10, 11, 12]}

Corresct answer is: a) {‘a’: [1, 2, 3, 4, 5], ‘b’: [6, 7, 8, 9, 10], ‘c’: [11, 12, 13, 14, 15]}
Explanation: The code creates three lists, `l1`, `l2`, and `l3`, and populates them with consecutive numbers using range(). Then, a dictionary `dict1` is created with keys ‘a’, ‘b’, and ‘c’, and their respective values are assigned as `l1`, `l2`, and `l3`. Finally, the dictionary is printed, resulting in `{‘a’: [1, 2, 3, 4, 5], ‘b’: [6, 7, 8, 9, 10], ‘c’: [11, 12, 13, 14, 15]}`.

Python Dictionary MCQ : Set 2

Python Dictionary MCQ

1). Which method returns a string representation of a dictionary?

a) str()
b) repr()
c) string()
d) __str__()

Corresct answer is: d) __str__()
Explanation: The __str__() method returns a string representation of a dictionary. It can be customized by overriding the method in a custom dictionary class.

2). Which method returns a dictionary’s iterator for keys?

a) keys()
b) iterate_keys()
c) key_iterator()
d) __iter__()

Corresct answer is: a) keys()
Explanation: The keys() method returns an iterator for the keys in a dictionary, allowing iteration over the keys.

3). Which method returns a dictionary’s iterator for values?

a) values()
b) value_iterator()
c) iterate_values()
d) __iter__()

Corresct answer is: a) values()
Explanation: The values() method returns an iterator for the values in a dictionary, allowing iteration over the values.

4). Which method returns a dictionary’s iterator for key-value pairs as tuples?

a) iteritems()
b) items()
c) iterate_pairs()
d) __iter__()

Corresct answer is: b) items()
Explanation: The items() method returns an iterator for the key-value pairs in a dictionary as tuples, allowing iteration over the key-value pairs.


5). Which method returns the sum of all the values in a dictionary?

a) sum()
b) total()
c) add_values()
d) __sum__()

Corresct answer is: a) sum()
Explanation: The sum() method can be used to calculate the sum of all the values in a dictionary.

6). In Python which method returns a new dictionary with only the specified keys and their values?

a) subset()
b) filter()
c) select()
d) __getitem__()

Corresct answer is: b) filter()
Explanation: The filter() method returns a new dictionary with only the specified keys and their corresponding values.

7). Which method returns a new dictionary with the specified default value for keys that are not present in the original dictionary?

a) set_default()
b) default()
c) default_value()
d) __missing__()

Corresct answer is: a) set_default()
Explanation: The set_default() method returns a new dictionary with the specified default value for keys that are not present in the original dictionary.

8). Which method returns the number of key-value pairs in a dictionary?

a) count()
b) size()
c) length()
d) __len__()

Corresct answer is: d) __len__()
Explanation: The __len__() method returns the number of key-value pairs in a dictionary.

9). Which method returns a copy of a dictionary?

a) clone()
b) copy()
c) duplicate()
d) __copy__()

Corresct answer is: b) copy()
Explanation: The copy() method returns a shallow copy of a dictionary.

10). Which method can be used to clear all the key-value pairs in a dictionary?

a) clear()
b) empty()
c) remove_all()
d) __clear__()

Corresct answer is: a) clear()
Explanation: The clear() method removes all the key-value pairs from a dictionary, making it empty.

11). Which method can be used to check if a specific value is present in a dictionary?

a) contains()
b) has_value()
c) in_value()
d) __contains__()

Corresct answer is: d) __contains__()
Explanation: The __contains__() method can be used to check if a specific value is present in a dictionary.

12). Which method can be used to combine two dictionaries into one?

a) combine()
b) merge()
c) join()
d) __add__()

Corresct answer is: b) merge()
Explanation: The merge() method can be used to combine two dictionaries into one.

13). Which method can be used to remove a specific key-value pair from a dictionary?

a) remove()
b) delete()
c) pop()
d) __remove__()

Corresct answer is: c) pop()
Explanation: The pop() method can be used to remove a specific key-value pair from a dictionary based on the given key.

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

dictionary = {‘a’: 5, ‘b’:3, ‘c’: 6, ‘d’: 8}
for val in dictionary:
print(val,”:”, dictionary[val]**2)

a) a: 5, b: 3, c: 6, d: 8
b) a: 25, b: 9, c: 36, d: 64
c) a: 5^2, b: 3^2, c: 6^2, d: 8^2
d) a: 25, b: 3, c: 36, d: 8

Corresct answer is: b) a: 25, b: 9, c: 36, d: 64
Explanation: The code iterates over the dictionary using a for loop. In each iteration, it prints the key followed by a colon and the square of the corresponding value. The output will be “a: 25, b: 9, c: 36, d: 64” because the values are squared before printing.

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

D1 = {‘name’:’john’,’city’:’Landon’,’country’:’UK’}
D2 = {}

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

a) {‘name’:’john’,’city’:’Landon’,’country’:’UK’}
b) {‘john’:’name’,’Landon’:’city’,’UK’:’country’}
c) {‘name’,’john’,’city’,’Landon’,’country’,’UK’}
d) {‘john’,’Landon’,’UK’}

Corresct answer is: a) {‘name’:’john’,’city’:’Landon’,’country’:’UK’}
Explanation: The code iterates over the key-value pairs in dictionary D1. It then assigns each key-value pair to the corresponding key in dictionary D2. Therefore, D2 will have the same key-value pairs as D1, resulting in the output {‘name’:’john’,’city’:’Landon’,’country’:’UK’}.

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

dict1 = {‘Name’:’Harry’,’Rollno’:345,’Address’:’Jordan’}
dict2 = {‘Age’:25,’salary’: ‘$25k’}
dict1.update(dict2)
print(dict1)

a){‘Name’:’Harry’,’Rollno’:345,’Address’:’Jordan’,’Age’:25,’salary’: ‘$25k’}
b) {‘Name’:’Harry’,’Age’:25,’Rollno’:345,’salary’: ‘$25k’,’Address’:’Jordan’}
c) {‘Name’:’Harry’,’Rollno’:345,’Address’:’Jordan’}
d) {‘Age’:25,’salary’: ‘$25k’}

Corresct answer is: a) {‘Name’:’Harry’,’Rollno’:345,’Address’:’Jordan’,’Age’:25,’salary’: ‘$25k’}
Explanation: The update() method is used to add the key-value pairs from dict2 into dict1. The original values in dict1 are updated with the corresponding values from dict2. Therefore, the output will be {‘Name’:’Harry’,’Rollno’:345,’Address’:’Jordan’,’Age’:25,’salary’: ‘$25k’}

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

dict1 = {1:25, 5:’abc’, 8:’pqr’, 21:’xyz’, 12:’def’, 2:’utv’}

list1 = [[val, dict1[val]] for val in dict1 if val%2 == 0]
list2 = [[val, dict1[val]] for val in dict1 if val%2 != 0]

print(“Even key = “, list1)
print(“Odd key = “, list2)

a) Even key = [[8, ‘pqr’], [12, ‘def’], [2, ‘utv’]]
Odd key = [[1, 25], [5, ‘abc’], [21, ‘xyz’]]
b) Even key = [[1, 25], [5, ‘abc’], [21, ‘xyz’]]
Odd key = [[8, ‘pqr’], [12, ‘def’], [2, ‘utv’]]
c) Even key = []
Odd key = [[1, 25], [5, ‘abc’], [21, ‘xyz’], [8, ‘pqr’], [12, ‘def’], [2, ‘utv’]]
d) Even key = [[1, 25], [5, ‘abc’], [21, ‘xyz’], [8, ‘pqr’], [12, ‘def’], [2, ‘utv’]]
Odd key = []

Corresct answer is: a) Even key = [[8, ‘pqr’], [12, ‘def’], [2, ‘utv’]]
Odd key = [[1, 25], [5, ‘abc’], [21, ‘xyz’]]
Explanation: In the given code, `list1` is generated using a list comprehension that iterates over the values in `dict1`. It only includes key-value pairs where the key is even. Similarly, `list2` is generated using a list comprehension that includes key-value pairs where the key is odd. The code then prints the contents of `list1` and `list2`. The output shows that `list1` contains the even key-value pairs and `list2` contains the odd key-value pairs from `dict1`.

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

list1 = [‘a’, ‘b’, ‘c’, ‘d’, ‘e’]
list2 = [12, 23, 24, 25, 15, 16]
dict1 = {}

for a, b in zip(list1, list2):
    dict1[a] = b

print(dict1)

a) {‘a’: 12, ‘b’: 23, ‘c’: 24, ‘d’: 25, ‘e’: 15}
b) {‘a’: 12, ‘b’: 23, ‘c’: 24, ‘d’: 25, ‘e’: 15, ’16’: None}
c) {‘a’: 12, ‘b’: 23, ‘c’: 24, ‘d’: 25, ‘e’: 15, ’16’: 16}
d) Error

Corresct answer is: a) {‘a’: 12, ‘b’: 23, ‘c’: 24, ‘d’: 25, ‘e’: 15}
Explanation: The code uses the `zip()` function to iterate over `list1` and `list2` simultaneously. It then assigns each element of `list1` as a key and each element of `list2` as a value in `dict1`. The resulting dictionary will be `{‘a’: 12, ‘b’: 23, ‘c’: 24, ‘d’: 25, ‘e’: 15}`.

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

list1 = [4, 5, 6, 2, 1, 7, 11]
dict1 = {}

for val in list1:
    if val % 2 == 0:
        dict1[val] = val**2
    else:
        dict1[val] = val**3
print(dict1)

a) {4: 16, 5: 125, 6: 36, 2: 4, 1: 1, 7: 343, 11: 1331}
b) {4: 8, 5: 9, 6: 10, 2: 4, 1: 1, 7: 49, 11: 121}
c) {4: 8, 5: 125, 6: 36, 2: 4, 1: 1, 7: 343, 11: 121}
d) {4: 16, 5: 9, 6: 10, 2: 4, 1: 1, 7: 343, 11: 1331}

Corresct answer is: a) {4: 16, 5: 125, 6: 36, 2: 4, 1: 1, 7: 343, 11: 1331}
Explanation: The code initializes an empty dictionary `dict1` and iterates over the elements of `list1`. For each element, if it is even (divisible by 2), the element is used as a key in `dict1` with its square value as the corresponding value. If it is odd, the element is used as a key with its cube value as the corresponding value. The final dictionary `dict1` will contain the following key-value pairs: `{4: 16, 5: 125, 6: 36, 2: 4, 1: 1, 7: 343, 11: 1331}`.

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

dict1 = {‘Name’: ‘Harry’, ‘Rollno’: 345, ‘Address’: ‘Jordan’}
dict1.clear()
print(dict1)

a) {}
b) {‘Name’: ‘Harry’, ‘Rollno’: 345, ‘Address’: ‘Jordan’}
c) Error
d) None

Corresct answer is: a) {}
Explanation: The `clear()` method removes all the key-value pairs from the dictionary, making it empty. Therefore, the output is an empty dictionary `{}`.

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

string = “SQAToolss”
dict1 = {}

for char in string:
    dict1[char] = string.count(char)

print(dict1)

a) {‘S’: 2, ‘Q’: 1, ‘A’: 1, ‘T’: 1, ‘o’: 2, ‘l’: 1, ‘s’: 2}
b) {‘S’: 1, ‘Q’: 1, ‘A’: 1, ‘T’: 1, ‘o’: 2, ‘l’: 1, ‘s’: 2}
c) {‘S’: 1, ‘Q’: 1, ‘A’: 1, ‘T’: 1, ‘o’: 1, ‘l’: 1, ‘s’: 2}
d) {‘S’: 1, ‘Q’: 1, ‘A’: 1, ‘T’: 1, ‘o’: 1, ‘l’: 1, ‘s’: 1}

Corresct answer is: a) {‘S’: 2, ‘Q’: 1, ‘A’: 1, ‘T’: 1, ‘o’: 2, ‘l’: 1, ‘s’: 2}
Explanation: The code initializes an empty dictionary `dict1` and iterates over each character in the string “SQAToolss”. For each character, it counts the number of occurrences in the string using the `count()` method and assigns the count as the value for that character in the dictionary. The final dictionary will contain the counts of each character in the string.

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

dict1 = {‘d’:14,’b’:52,’a’:13,’c’: 1}
sorted_ = {key: value for key, value in sorted(dict1.items(), key=lambda item: item[1])}
print(sorted_)

a) {‘c’: 1, ‘a’: 13, ‘d’: 14, ‘b’: 52}
b) {‘a’: 13, ‘b’: 52, ‘c’: 1, ‘d’: 14}
c) {‘b’: 52, ‘d’: 14, ‘a’: 13, ‘c’: 1}
d) {‘c’: 1, ‘b’: 52, ‘a’: 13, ‘d’: 14}

Corresct answer is: a) {‘c’: 1, ‘a’: 13, ‘d’: 14, ‘b’: 52}
Explanation: The code snippet sorts the dictionary `dict1` based on the values in ascending order using a lambda function as the sorting key. The resulting dictionary `sorted_` will have key-value pairs sorted by their values from smallest to largest.The output will be `{‘c’: 1, ‘a’: 13, ‘d’: 14, ‘b’: 52}`.

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

D1 = {‘x’: 23, ‘y’: 10, ‘z’: 7}
total = 0
for val in D1.values():
    total += val
print(total)

a) 23
b) 40
c) 50
d) 7

Corresct answer is: b) 40
Explanation: The code calculates the sum of all the values in the dictionary D1. The values are accessed using the values() method and then added to the total variable using a loop. The sum of 23 + 10 + 7 is 40, which is printed as the output.

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

D1 = {‘city’:’pune’,’state’:’maharashtra’}
count = 0

for key in D1.keys():
    if key == “Country”:
        count += 1

if count > 0:
print(“Key exists”)
else:
print(“Key does not exist”)

a) Key exists
b) Key does not exist
c) Error
d) None

Corresct answer is: b) Key does not exist
Explanation: In the given code, the loop iterates over the keys of the dictionary `D1`. It checks if any key is equal to “Country”. Since there is no key with the name “Country” in the dictionary, the `count` variable remains 0. After the loop, the code checks if `count` is greater than 0. Since it is not, the output will be “Key does not exist”.

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

n = 4
D1 = {}

for i in range(1, n+1):
    D1.update({i: i**3})
print(D1)

a) {1: 1, 2: 4, 3: 9, 4: 16}
b) {1: 1, 2: 8, 3: 27, 4: 64}
c) {1: 1, 2: 9, 3: 27, 4: 81}
d) {1: 1, 2: 16, 3: 81, 4: 256}

Corresct answer is: b) {1: 1, 2: 8, 3: 27, 4: 64}
Explanation: The code initializes an empty dictionary, `D1`. It then iterates over the numbers from 1 to 4 (inclusive) using the `range()` function. For each number, it updates the dictionary `D1` with a key-value pair, where the key is the number itself, and the value is the cube of the number. After the loop, the resulting dictionary `D1` will contain the key-value pairs `{1: 1, 2: 8, 3: 27, 4: 64}`.

Python Dictionary MCQ : Set 1

Python Dictionary MCQ

1). What is a dictionary in Python?

a) An ordered collection of elements
b) A sequence of key-value pairs
c) A data structure for storing integers
d) A built-in function in Python

Corresct answer is: b) A sequence of key-value pairs
Explanation: A dictionary in Python is an unordered collection of key-value pairs, where each key is unique.

2). Which symbol is used to define a dictionary in Python?

a) []
b) ()
c) {}
d) //

Corresct answer is: c) {}
Explanation: Curly braces ({}) are used to define a dictionary in Python.

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

my_dict = {‘name’: ‘Ketan’, ‘age’: 29}
print(my_dict[‘name’])

a) ‘name’
b) ‘John’
c) {‘name’: ‘John’}
d) 25

Corresct answer is: b) ‘Ketan’
Explanation: The code accesses the value associated with the key ‘name’ in the dictionary and prints it, which is ‘John’.

4). Can a dictionary contain duplicate keys?

a) Yes
b) No

Corresct answer is: b) No
Explanation: Dictionary keys must be unique. If a duplicate key is encountered during assignment, the last value assigned to that key will be retained.

5). How do you add a new key-value pair to a dictionary?

a) Using the append() method
b) Using the add() method
c) Using the insert() method
d) By assigning a value to a new key

Corresct answer is: d) By assigning a value to a new key
Explanation: To add a new key-value pair to a dictionary, you can simply assign a value to a new key using the assignment operator (=).

6). What happens when you access a key that does not exist in a dictionary?

a) An error is raised
b) None is returned
c) An empty string is returned
d) The dictionary expands to include the new key

Corresct answer is: a) An error is raised
Explanation: Accessing a key that does not exist in a dictionary raises a KeyError.

7). Which of the following methods in Python is used to remove a key-value pair from a dictionary?

a) delete()
b) remove()
c) discard()
d) del

Corresct answer is: d) del
Explanation: The `del` keyword is used to remove a key-value pair from a dictionary by specifying the key to be deleted.

8). What is the purpose of the keys() method in a dictionary?

a) To retrieve all the keys in a dictionary
b) To retrieve all the values in a dictionary
c) To retrieve both the keys and values in a dictionary
d) To sort the dictionary keys in ascending order

Corresct answer is: a) To retrieve all the keys in a dictionary
Explanation: The keys() method returns a view object that contains all the keys in the dictionary.

9). Which method returns a list of all the values in a dictionary?

a) values()
b) items()
c) get()
d) keys()

Corresct answer is: a) values()
Explanation: The values() method returns a view object that contains all the values in the dictionary.

10). Which method can be used to iterate over both the keys and values in a dictionary?

a) items()
b) keys()
c) values()
d) iterate()

Corresct answer is: a) items()
Explanation: The items() method returns a view object that contains key-value pairs as tuples, allowing iteration over both keys and values.

11). Which method returns the value associated with a specified key in a dictionary?

a) get()
b) value()
c) fetch()
d) retrieve()

Corresct answer is: a) get()
Explanation: The get() method returns the value associated with a specified key in a dictionary. If the key does not exist, it can return a default value.

12). Which method can be used to check if a key exists in a dictionary?

a) has_key()
b) contains()
c) in
d) exists()

Corresct answer is: c) in
Explanation: The `in` operator can be used to check if a key exists in a dictionary. It returns a Boolean value (True or False).

13). Which method is used to clear all the key-value pairs from a dictionary?

a) clear()
b) delete()
c) remove()
d) empty()

Corresct answer is: a) clear()
Explanation: The clear() method removes all the key-value pairs from a dictionary, making it an empty dictionary.

14). Which method is used to update a dictionary with the key-value pairs from another dictionary?

a) merge()
b) update()
c) add()
d) append()

Corresct answer is: b) update()
Explanation: The update() method is used to update a dictionary with the key-value pairs from another dictionary.

15). Which method returns a shallow copy of a dictionary?

a) copy()
b) clone()
c) duplicate()
d) replicate()

Corresct answer is: a) copy()
Explanation: The copy() method returns a shallow copy of a dictionary, creating a new dictionary with the same key-value pairs.

16). Which of the following is an immutable data type and can be used as a key in a dictionary?

a) List
b) Tuple
c) Set
d) Dictionary

Corresct answer is: b) Tuple
Explanation: Tuples are immutable data types and can be used as keys in a dictionary. Lists, sets, and dictionaries are mutable and cannot be used as keys.

17). Which method returns a new dictionary with keys and values swapped?

a) switch()
b) swap()
c) reverse()
d) reversed()

Corresct answer is: c) reverse()
Explanation: The reverse() method returns a new dictionary where the keys and values are swapped.

18). Which method can be used to create a dictionary from two lists, one containing keys and the other containing values?

a) dict()
b) create()
c) make()
d) generate()

Corresct answer is: a) dict()
Explanation: The dict() function can be used to create a dictionary from two lists, where one list contains keys and the other contains values.

19). Which method returns the minimum key in a dictionary?

a) min_key()
b) smallest_key()
c) min()
d) min_key()

Corresct answer is: c) min()
Explanation: The min() method returns the minimum key in a dictionary based on their natural ordering.

20). Which method returns the maximum value in a dictionary?

a) max_value()
b) largest_value()
c) max()
d) max_value()

Corresct answer is: c) max()
Explanation: The max() method returns the maximum value in a dictionary based on their natural ordering.

21). Which method is used to sort the keys in a dictionary in ascending order?

a) sort()
b) sort_keys()
c) sorted()
d) order()

Corresct answer is: b) sort_keys()
Explanation: The sort_keys() method is used to sort the keys in a dictionary in ascending order.

22). Which method is used to sort the values in a dictionary in ascending order?

a) sort_values()
b) sort()
c) sorted()
d) order_values()

Corresct answer is: a) sort_values()
Explanation: The sort_values() method is used to sort the values in a dictionary in ascending order.

23). Which method is used to reverse the order of the keys in a dictionary?

a) reverse_keys()
b) reverse()
c) reversed()
d) invert_keys()

Corresct answer is: c) reversed()
Explanation: The reversed() method returns a reversed view object for the keys in a dictionary.

24). Which method can be used to perform a shallow comparison between two dictionaries?

a) compare()
b) equals()
c) compare_dicts()
d) __eq__()

Corresct answer is: d) __eq__()
Explanation: The __eq__() method can be used to perform a shallow comparison between two dictionaries for equality.

25). Which method returns a hash value for a dictionary?

a) hash()
b) get_hash()
c) calculate_hash()
d) __hash__()

Corresct answer is: d) __hash__()
Explanation: The __hash__() method returns a hash value for a dictionary, allowing it to be used as a key in another dictionary or a member of a set.