Explaining differences between dict.get(key) and dict[key] in Python
2 min readFeb 8, 2023
The aim of this explainer💡 is to define the difference between
<dict>.get(<key>) VS <dict>[<key>]
in Python.
1. Get() is used when the missing key should not throw an exception, [] syntax when it should
- It allows you to provide a default value/expression if the key is missing
- …a sort of if/then mechanism without an if statement
>>> d = {"name": "mr_paul"}
>>> d.get("name")
'mr_paul'
>>> d.get("job", print("seems to be unemployed"))
seems to be unemployed
- If omitted in the
.get()
,default_value
isNone
, such that
>>> d.get("job", None)
- is the same as
>>> d.get("job") # <-- No default specified -- defaults to None
- however, checking for a non-existent key with
[]
syntax throws an ERROR
>>> d["name"]
'mr_paul'
>>> d["job"]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
KeyError: 'job'
'job'
- raises a
KeyError
which you can properly catch if needed
2. Let’s get to real life: I am get()
this for say checking a value of an environmental variable
- I’m in a Docker
- I am doing case analysis based on environmental variables and I don’t want the script to crash if a key is not found
if os.environ.get("IMAGE_NAME") == "my_foo_docker image":
return input('Please enter client tag (e.g. com_acme): ')
else:
return input("Please enter org id: ")
- A simple reason is that I can look_up org_id in one container based on a nicer client tags
3. In addition, you can return values for non-found keys by using get()
- the following counts words in a string
def count_words(doc):
normalised_doc = "".join(c.lower() if c.isalpha() else " " for c in doc)
frequencies = {}
for word in normalised_doc.split():
frequencies[word] = frequencies.get(word, a0) + 1
return frequencies
frequencies.get(word, 0)
means thatKeyError
is never raised because of the use ofget
method- the
0
is another optional parameter to be returned as a value if the key does not exist - the default is
None