Tip: You should use dict.get(key) instead of dict[key]

Isabelle Viktoria Maciohsek · Python, Dictionary · Jun 12, 2021

A common debate among Python developers seems to stem from the retrieval of dictionary values, which can be accomplished using either dict[key] or dict.get(key).

Although you can achieve the same result using either one, dict.get() is usually preferred, as it accepts a second argument which acts as the default value shall the key not exist in the given dictionary. Due to this property, dict.get() will always return a value, whereas dict[key] will raise a KeyError if the given key is missing.

a = { 'max': 200 }
b = { 'min': 100, 'max': 250 }
c = { 'min': 50 }

a['min'] + b['min'] + c['min'] # throws KeyError
a.get('min', 0) + b.get('min', 0) + c.get('min', 0) # 150

Recommended snippets & collections

  • Tips & Tricks

    Snippet collection

    A collection of quick tips and tricks to level up your coding skills one step at a time.

  • Combine dictionary values

    Python, Dictionary

    Combines two or more dictionaries, creating a list of values for each key.

  • Get nested value

    Python, Dictionary

    Retrieves the value of the nested key indicated by the given selector list from a dictionary or list.

  • Map dictionary values

    Python, Dictionary

    Creates a dictionary with the same keys as the provided dictionary and values generated by running the provided function for each value.