What will be the output of the following Python code?
d = {"name": "Ravi", "age": 20, "city": "Delhi"}
d1 = d.copy()
d1.clear()
print(d)
print(d1)
A) {"name": "Ravi", "age": 20, "city": "Delhi"}
{}
B) {}
{}
C) {"name": "Ravi", "age": 20, "city": "Delhi"}
{"name": "Ravi", "age": 20, "city": "Delhi"}
D) {}
{"name": "Ravi", "age": 20, "city": "Delhi"}
Answer:
Answer by student
A) {“name”: “Ravi”, “age”: 20, “city”: “Delhi”}
{}
Detailed answer by teachoo
- A dictionary is a collection of key-value pairs that are unordered, changeable, and indexed.
- There are many built-in functions/methods that can be used to manipulate dictionaries in Python.
- In this question, we are using the built-in methods copy() and clear() on a dictionary object. The syntax of these methods are:
dictionary.copy()
dictionary.clear()
where, dictionary is the original dictionary. The method copy() returns a shallow copy of the dictionary , which means it creates a new dictionary with the same key-value pairs as the original dictionary , but does not copy the references to the values. The method clear() removes all the key-value pairs from the dictionary and makes it empty.
- Now that we know these concepts, we can proceed to find out the output of the code. We will follow these steps:
- First, we will create a dictionary with three key-value pairs and assign it to the variable d using the statement d = {"name": "Ravi", "age": 20, "city": "Delhi"} .
- Next, we will call the method copy() on d and assign the result to the variable d1 using the statement d1 = d.copy() . This will create a new dictionary with the same key-value pairs as d and assign it to d1. The dictionaries d and d1 will have different memory locations and any changes made to one will not affect the other.
- Then, we will call the method clear() on d1 using the statement d1.clear() . This will remove all the key-value pairs from d1 and make it an empty dictionary. The dictionary d will remain unchanged.
- Finally, we will display the values of d and d1 using the statements print(d) and print(d1) . This will print:
{"name": "Ravi", "age": 20, "city": "Delhi"}
{}
- Therefore, option A) is the correct answer.
So, the correct answer is
A) {“name”: “Ravi”, “age”: 20, “city”: “Delhi”}
{ }