[Python] Why dict.get(key) instead of dict[key]?

Discussão em 'Python' iniciado por Stack, Março 2, 2025.

  1. Stack

    Stack Membro Participativo

    I came across the dict method get which, given a key in the dictionary, returns the associated value.

    For what purpose is this function useful? If I wanted to find a value associated with a key in a dictionary, I can just do dict[key], and it returns the same thing:

    dictionary = {"Name": "Harry", "Age": 17}
    dictionary["Name"] == dictionary.get("Name") # True


    See also: Return a default value if a dictionary key is not available

    Continue reading...

Compartilhe esta Página