DEV Community

Vladimir Ignatev
Vladimir Ignatev

Posted on • Updated on

🤔 Python Quiz: ⚗️ Dicts Alloy

Follow me to learn 🐍 Python in 5-minute a day fun quizzes! Find previous quiz here.

Python 3.9 introduced new operators for dictionary merging. You'll learn more about making alloys from your dicts by reading the original PEP-0584. PEP-0584 simplifies dictionary operations, enhancing Python's ease of use and readability..

Quiz

Which one of these code samples correctly demonstrates the use of Python's dictionary merging as guided by PEP 584?

Sample 1

dict1 = {'a': 1, 'b': 2}
dict2 = {'b': 3, 'c': 4}
merged_dict = dict1 | dict2
Enter fullscreen mode Exit fullscreen mode

Sample 2

dict1 = {'a': 1, 'b': 2}
dict2 = {'b': 3, 'c': 4}
merged_dict = dict1 + dict2
Enter fullscreen mode Exit fullscreen mode

Post your answer in the comments! 0 if you think that Sample 1 is correct, 1 otherwise. As usually, the correct answer will be explained in the first comment.

Top comments (2)

Collapse
 
vladignatyev profile image
Vladimir Ignatev

Okay-okay. Here is the explanation!

The correct answer is Sample 1.

PEP-584 proposes the addition of the | and |= operators as a succinct way to merge two dictionaries. It's a feature added to Python 3.9, allowing for easier and more intuitive dictionary merging.

In Sample 1, the | operator is correctly used to merge dict1 and dict2. When dictionaries are merged using |, the elements of the second dictionary are effectively added to the first. In case of overlapping keys, the values from the second dictionary will overwrite those from the first.

In Sample 2, the + operator is incorrectly used for merging dictionaries. Python's dict class does not support the + operator for merging dictionaries, and this code would result in a TypeError.

Therefore, Sample 1 is the correct one as it adheres to the guidelines of PEP 584 and demonstrates the proper usage of the | operator for dictionary merging.

Collapse
 
vladignatyev profile image
Vladimir Ignatev

I've noticed that nobody posted comment yet. Let's wait for the first one, and after that I'll show an explanation!