Python Dictionary: Why accessing with [] is a bad idea

Andrés Gutiérrez
2 min readMar 12, 2022

Short answer: It will raise an error if key does not exist causing failure in your app

Dictionaries in Python are key — value data structures. You can think that dictionaries are like JSON.

Dictionary keys must be immutable data type and values can any kind of data type, even functions references.

This is a dictionary sample

my_dict = {
"a": 1,
"n": "Andres",
"d": [],
"r": {},
"e": lambda x: x,
"s": (1,)
}

It’s Friday and you want to deliver your feature as soon as possible. You are tempted to access values in a particular dictionary using square brackets because it’s fast and we use less characters. You didn’t use the built-in get method from dict.

After pushing the code to development, you noticed that there is an error in the app logs and your app is broken; you know that this will require another deployment, as a consequence, time wasted.

KeyError: '<my_key>'

What happened?

Well, for accessing data in dict, we have two approaches:

  1. Using square brackets []
  2. Using built-in get() method

If we go to [] approach, we need to make sure that the key exists, otherwise, this will raise an error because it is using direct access to dict. Bad idea to use it, right?

In another hand, if we use get() method, in case we request a key that does not exist, it will return None which is better than an exception.

my_dict = {
"a": 1,
"n": "Andres",
"d": [],
"r": {},
"e": lambda x: x,
"s": (1,)
}
a = my_dict.get("a")

Another advantage of using get() method is that it supports a second argument, the default return value.

In case key does not exist, we can supply a default return value.

a = my_dict.get("a", 100)

In the example above, if key ‘a’ is not in the dictionary, a will store 100.

Our time is valuable, let’s do not waste the time fixing ‘KeyError’, and for those who review code in PR, make sure you spot this issue sooner.

--

--

Andrés Gutiérrez

Software developer, Pythonista, bug-resolver.I'm currently working in backend and frontend tasks. First steps in DevOps