Every week we publish a Python quiz in my twitter account. Only for fun!
The summary of question for this weed was:
- Subject: Dictionaries
- Difficulty: 2/5
You can reach the question at the original tweet:
Correct answer
Ok. Spoiler here. Correct answer is Option C. But, why…?
A brief explanation
Before all, the question assumes we’re using Python 3. Python 2 was dead, oks?
Why Option A is incorrect
It looks like:
a = {“one”: “two”}
b = {“nine”: “ten”}
merged = a | b
Ok. This choice was a bit tricky. Syntax a | b
is new in Python 3.9. So, this answer is correct.
You can find more info at official Python documentation:
So: this option is true. Then is not a valid answer
Option B
It looks like:
a = {“one”: “two”}
b = {“nine”: “ten”}
merged = {**a, **b}
In Python 3.5 was introduced this syntax. So this options is also true (or True? :D)
So: this option is true. Then is not a valid answer
Option C
It looks like:
a = {“one”: “two”}
b = {“nine”: “ten”}
merged = a + b
Operator add (+) is not implemented for Python dictionaries. So, if you try to do that you’ll get an error like:
>>> a = {“one”: “two”}
>>> b = {“nine”: “ten”}
>>> a + b
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: unsupported operand type(s) for +: 'dict' and 'dict'
So: this option is false. Then is the correct answer
Extra: Making Option C true
As I said, operator add is not implemented for dictionaries in Python by default. But you can overload it. It’s ver easy:
class dictp(dict):
def __add__(self, o: dict):
tmp = self.copy()
tmp.update(o)
return tmp
Now you must use dictp
instead of regular dict
:
>>> a = dictp()
>>> a["one"] = 1
>>> b = dictp()
>>> b["two"] = 2
>>> print(a + b)
{'one': 1, 'two': 2}
Any question or suggestion? Leave me a comment!