Python Language Idioms Dictionary key initializations

Help us to keep this website almost Ad Free! It takes only 10 seconds of your time:
> Step 1: Go view our video on YouTube: EF Core Bulk Extensions
> Step 2: And Like the video. BONUS: You can also share it!

Example

Prefer dict.get method if you are not sure if the key is present. It allows you to return a default value if key is not found. The traditional method dict[key] would raise a KeyError exception.

Rather than doing

def add_student():
    try:
        students['count'] += 1
    except KeyError:
        students['count'] = 1

Do

def add_student():
        students['count'] = students.get('count', 0) + 1


Got any Python Language Question?