Don’t Use This Syntax To Access A Dictionary Value In Python

Use .get() instead

Amir Ali Hashemi
1 min readDec 31, 2022
Image by author

Suppose we have the below dictionary and we want to get the value associated with is_capital .

city = {
'name' : 'New York',
'country' : 'The United States',
'is_capital' : False,
'population' : 8.468
}

x = city['is_capital']
print(x)

When we run the code snippet above it would output: False , which is the value we were expecting.

So what’s wrong with the syntax then? Well, there is nothing wrong with using this syntax but check this example out: if we use a key that does’t exist in the dictionary it will return a key error.

x = city['area']
print(x)
Traceback (most recent call last):
x = city['area']
KeyError: 'area'

We can fix the error by using .get() on our dictionary instead.

x = city.get('area')
print(x)

If the key doesn’t exist in the dictionary, by default, it would just give you None .

You can also add a second variable here to use in place of None :

x = city.get('area', 0)
print(x)

Output: 0

--

--

Amir Ali Hashemi
Amir Ali Hashemi

Written by Amir Ali Hashemi

I'm an AI student who attempts to find simple explanations for questions and share them with others