Python Dictionary Get: A Complete Guide

Posted in /  

Python Dictionary Get: A Complete Guide
vinaykhatri

Vinay Khatri
Last updated on April 26, 2024

    Python dictionary supports a get method, that returns the value mapped to a key. The get() method is an alternative to square bracket notation when we want to access a dictionary value using the key name.

    Often we use the square brackets to access a value from a dictionary. In square bracket notation, we pass the key name inside the square brackets, such as dict_name[keyName] . But Python dictionary also provides an inbuilt get() method that also accepts the key name and returns the value associated with the key.

    Professional Python developers prefer using the get() method over square bracket notation when accessing the value from a dictionary. Because the get() method returns the key's value if the key is present in the dictionary; otherwise, it returns None or a default value. In this Python tutorial, we will walk through the Python dict.get() method and learn how to use it.

    Python Dictionary get() method

    Python dictionary store its elements in the form of key:value pairs, and to retrieve a dictionary value using a key, we can either use the square bracket notation or the dictionary get() method. Syntax

    dictnonary_name.get(key, default)

    The dictionary get() method can accept two argument values.

    1. key : The argument specifies the key name and which associated value we want to retrieve from the dictionary
    2. default (optional): This is an optional argument, and its default value is None. This argument specifies a value that will return if the specified key is not present in the dictionary.

    Return

    The get() method return the associated value of the specified key if the key is present in the dictionary; otherwise, it returns the value of the default argument i.e. None.

    Example: Get a value from a Python Dictionary

    Now let's create a dictionary and access its elements using the get() method.

    customer = {
                "name": "Nancy",
                "balance": "$2,481.32",
                "age": 26,
                "gender": "female",
                "email": "Nancy@mail.com",
                }
    print("--------Customer Details----------")
    print("Name:", customer.get('name'))
    print("Age:", customer.get('age'))
    print("Email:", customer.get('email'))
    print("Balance:", customer.get('balance'))
    print("Loan:", customer.get('loan'))  #no loan key in the  dictionary
    

    Output

    --------Customer Details----------
    Name: Nancy
    Age: 26
    Email: Nancy@mail.com
    Balance: $2,481.32
    Loan: None

    In the above example, we are accessing the customer dictionary details using the get() method.  In this example, we have accessed the customer's Name, Age, Email, Balance, and Loan using name , age , email , balance and loan keys. But in the customer dictionary we have no key with loan name, in that statement, the customer.get('loan') statement returns None . If a dictionary does not have the specified key passed in the get() method as an argument, the method returns the None value. If you do not want the None value, you can also specify the default argument value for non-existent keys.

    Example

    Now, let's define a default argument for the customer.get('loan') statement for which we were getting the None value in the above example.

    customer = {
                "name": "Nancy",
                "balance": "$2,481.32",
                "age": 26,
                "gender": "female",
                "email": "Nancy@mail.com",
                }
    print("--------Customer Details----------")
    print("Name:", customer.get('name'))
    print("Age:", customer.get('age'))
    print("Email:", customer.get('email'))
    print("Balance:", customer.get('balance'))
    print("Loan:", customer.get('loan', "No Loan Amount"))  #no loan key in the  dictionary
    

    Output

    --------Customer Details----------
    Name: Nancy
    Age: 26
    Email: Nancy@mail.com
    Balance: $2,481.32
    Loan: No Loan Amount

    Python Dictionary get(key) method Vs Square bracket Notation dict[key]

    We can either use the square brackets or get() method to access an individual dictionary value using a key name. But there are some differences between them that you should know before using one. The get() method accepts the key name as an argument and returns its associative value if the key is present in the dictionary.

    If the key does not exist in the dictionary, the get() method returns the None value or the value specified as a default argument. With square bracket notation, dict[key] we can also access the dictionary value using a key. But in the square bracket, if we pass a key name that does not exist in the dictionary the square bracket notation return the KeyError.

    Example(Invalid key with get() method)

    customer = {
                "name": "Nancy",
                "balance": "$2,481.32",
                "age": 26,
                "gender": "female",
                "email": "Nancy@mail.com",
                }
    
    print("Name:",customer.get('Name')) #invalid Name key
    

    Output

    Name: None

    Example(Invalid key with Square brackets)

    customer = {
                "name": "Nancy",
                "balance": "$2,481.32",
                "age": 26,
                "gender": "female",
                "email": "Nancy@mail.com",
                }
    
    print("Name:",customer['Name'])   #invalid Name key
    

    Output

    Traceback (most recent call last):
      File "main.py", line 9, in 
        print("Name:",customer['Name'])   #invalid Name key
    KeyError: 'Name'
    

    Conclusion

    The Python dictionary's get method is used to retrieve a specific value from a dictionary by passing the key name as the argument. The get() method is error-free and more efficient as compared to the square bracket notation. The get() method does not return an error if the passed key name does not exist in the dictionary. Instead, it returns None.

    People are also reading:

    Leave a Comment on this Post

    0 Comments