Python Language Idioms Dictionary key initializations

30% OFF - 9th Anniversary discount on Entity Framework Extensions until December 15 with code: ZZZANNIVERSARY9


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():
        students['count'] += 1
    except KeyError:
        students['count'] = 1


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

Got any Python Language Question?