Why To Use dict.get() method in Python Dictionary and Not just dict[] ?
<dict>.get(<key>) — VS — <dict>[<key>]
1 min readOct 28, 2021
NOTES
- It allows you to provide a default value/expression if the key is missing
- …a sort of if/then mechanism without 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
RETURN VALUE FOR NON-FOUND KEYS IN get()
- see Understanding .get() method in Python — Stack Overflow
- this 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, 0) + 1
return frequencies
frequencies.get(word, 0)
means thatKeyError
is never raised because of the use ofget
method- and, the
0
is another optional parameter to be returned as a value if the key does not exist (the default isNone
) - This is the primitive example combining these behaviors:
>>> d = {"name":"pavol"}
>>> d.get("age")>>> d.get("age",0)
0
>>> d["age"]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
KeyError: 'age''age'