Python From Beginner to Advanced

0% completed

Previous
Next
Python - Dictionary Operators

Dictionaries in Python do not support arithmetic operators like concatenation (+) or repetition (*) as lists do. However, Python provides membership operators (in, not in) for checking the presence of keys efficiently.

Additionally, Python 3.9+ introduced the | (union) operator, allowing dictionaries to be merged in a convenient way. These operators help in checking key existence and combining dictionaries without modifying the original structures.

1. Checking Key Presence with "in" Operator

The in operator is used to check whether a specific key exists in the dictionary. It returns True if the key is found, otherwise False.

Example 1: Using "in" to Check Key Presence

Python3
Python3

. . . .

Explanation

  • "Alice" in student_scores returns True because "Alice" exists in the dictionary.
  • "Dave" in student_scores returns False since "Dave" is not a key in the dictionary.

2. Checking Key Absence with "not in" Operator

The not in operator checks if a key is missing from the dictionary. It returns True if the key is absent.

Example 2: Using "not in" to Check Key Absence

Python3
Python3

. . . .

Explanation

  • "Dave" not in student_scores returns True because "Dave" is not a key in the dictionary.
  • "Bob" not in student_scores returns False since "Bob" exists in the dictionary.

3. Merging Dictionaries Using the "|" (Union) Operator (Python 3.9+)

Python 3.9+ introduced the | operator, which allows merging two dictionaries into a new dictionary.

Example 3: Merging Dictionaries with "|"

Python3
Python3

. . . .

Explanation

  • dict1 | dict2 merges both dictionaries into a new dictionary.
  • The original dictionaries remain unchanged.

These operators help check key presence efficiently and merge dictionaries easily, making them useful for working with large datasets, configurations, and lookups.

.....

.....

.....

Like the course? Get enrolled and start learning!
Previous
Next