Prometheus
Prometheus

Reputation: 33655

Difference between get and []

New to Django, can someone explain the difference between

username=form.cleaned_data['username']

vs

username=form.cleaned_data.get('username')

Upvotes: 1

Views: 1192

Answers (3)

Raunak Agarwal
Raunak Agarwal

Reputation: 7238

form.cleaned_data is a dictionary. If you try to access the key directly through dictionary like this, it would raise an error if the key is not found.

>>> ex_dict = {}
>>> ex_dict = {'x':1, 'y':2}
>>> ex_dict['z']

Traceback (most recent call last):
  File "<console>", line 1, in <module>
KeyError: 'z'

Whereas, if you use get with the dictionary, it would return None and not the error or you can specify the return you expect if key is not found.

>>> ex_dict.get('z')
>>> ex_dict.get('z', 1)
1

Upvotes: 4

Aamir Rind
Aamir Rind

Reputation: 39689

This will raise a KeyError if username key is not found

form.cleaned_data['username']

But this will return None (by default) if key is not found, does not raises KeyError exception.

form.cleaned_data.get('username')

Optionally you can change the default return value (if you use .get) if key is not found.

val = form.cleaned_data.get('username', False)
# assume key was not found
print val # should contains False now

Upvotes: 3

Ignacio Vazquez-Abrams
Ignacio Vazquez-Abrams

Reputation: 799150

From the docs:

get(key[, default])

Return the value for key if key is in the dictionary, else default. If default is not given, it defaults to None, so that this method never raises a KeyError.

Upvotes: 2

Related Questions