Why dict.get(key) instead of dict[key] in Python Dictionaries – Differences Explained

Python dictionary provides the get() method and the bracket method to access dictionary items.

The main difference between dict.get(key) and dict[key] is dict.get() allows you to provide a default value that needs to be returned when the key is unavailable. But the brackets method doesn’t provide a default.

This tutorial teaches the differences between the dict.get(key) and the dict[key] methods and why you should always use dict.get(key) instead of dict[key] in Python Dictionaries.

Dict Get vs Brackets

dict.get()dict[key]
Doesn’t raise keyerror when the key is unavailable in the dictionaryRaises the KeyError exception when the key is unavailable in the dictionary
Returns None when the key is unavailable in the dictionaryDoesn’t return None. Only raises an exception
Allows to specify a default value to use when the key is unavailableIt doesn’t allow to specify a default value to use when the key is unavailable

Dict.get(key)

You can use the dict.get() method to get the value of the key in the dictionary.

It accepts two parameters.

  • Key – Key for which the value needs to be fetched from the dictionary
  • defaultOptional – Default value when the key is unavailable in the dictionary. If this value is not provided, it defaults to None.

The get() method never raises an exception KeyError

Code

The following code demonstrates how the get() method works when the unavailable key is passed, and the default value is NOT provided.

yourdict = {
    "one": 1,
    "two": 2,
    "three": 3,
    "four": 4
}

print(yourdict.get('fourr'))

Output

None is returned as the key fourr is unavailable, and the default is NOT specified in the get() method.

    None

Code

The following code demonstrates how the get method returns the value of the key passed when it is available.

print(yourdict.get('four'))

Output

    4

Dict[key]

You can use the brackets [ ] to get the value of the key from the dictionary.

It raises a KeyError when the key is unavailable in the dictionary.

It doesn’tprovide an option to pass the default value to use when the key is unavailable.

You need to enclose the dict[key] statement in try and catch to avoid runtime errors in your program. Or, you need to Check If Key Exists in Dictionary before accessing it to avoid errors.

Code

The following code demonstrates the raising of the KeyError when the key is unavailable in the dictionary.

yourdict = {
    "one": 1,
    "two": 2,
    "three": 3,
    "four": 4
}

print(yourdict['fourr'])

Output

    ---------------------------------------------------------------------------
    KeyError      
    /var/folders/gb/19ly8vfs7t53plwx43wx1q3m0000gn/T/ipykernel_37764/4216818628.py in <module>

    ----> 8 print(yourdict['fourr'])


    KeyError: 'fourr'

Code

When you pass the key available in the dictionary, it returns the value without issues.

print(yourdict['four'])

Output

    4

Dict Get or Default

To return a default value if a dictionary key is not available, you can use the get() method and pass the default value in it.

Code

The following code demonstrates how to pass the default value to the dict.get() method.

yourdict = {
    "one": 1,
    "two": 2,
    "three": 3,
    "four": 4
}

print(yourdict.get('fourr', 'No Such Key Found'))

Output

The key fourr is unavailable in the dictionary. Hence the default value is returned.

    No Such Key Found

Dictionary Get Default If None

The dict.get() method returns None when the key is unavailable in the dictionary.

To get the default value, if the return value is None, you can pass the default value to the dict.get() method.

Code

The following code demonstrates the returning of None when the key is unavailable.

yourdict = {
    "one": 1,
    "two": 2,
    "three": 3,
    "four": 4
}

print(yourdict.get('fourr'))

Output

    None

You can pass the default value to return instead of None when the key is unavailable.

yourdict = {
    "one": 1,
    "two": 2,
    "three": 3,
    "four": 4
}

print(yourdict.get('fourr', 'No Such Key Found'))

Output

    No Such Key Found

Conclusion

You’ve learned the differences between the dict.get() method and the dict[key] method for accessing the dictionary items.

The main difference is dict.get() allows you to specify a default value. This avoids runtime exceptions in your program. That is why you should always use dict.get(key) instead of dict[key] in Python Dictionaries.

You’ve also learned how to use the dict.key() method to return the default value when the key is unavailable in the dictionary.

You May Also Like

Leave a Comment