Why To Use dict.get() method in Python Dictionary and Not just dict[] ?

<dict>.get(<key>) — VS — <dict>[<key>]

Pavol Kutaj
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 is None, 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()

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 that KeyError is never raised because of the use of get method
  • and, the 0 is another optional parameter to be returned as a value if the key does not exist (the default is None )
  • 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'

--

--

No responses yet