3

I tried to get data from API

1 request.data['param-name']

output -:'9121009000'

2 request.data.get('param-name')

output -:'9121009000'

Both are giving the same result.

So Which one is the best to use get data and Why.

Thanks in advance

Mr Singh
  • 3,936
  • 5
  • 41
  • 60
  • 1
    Possible duplicate of [Why dict.get(key) instead of dict\[key\]?](https://stackoverflow.com/questions/11041405/why-dict-getkey-instead-of-dictkey) – khelwood May 30 '18 at 10:48

2 Answers2

6

If you perform a request.data['key'] call, behind the curtains, Python will call the __getitem__ function of request.data. We can read the documentation and see:

QueryDict.__getitem__(key)

Returns the value for the given key. If the key has more than one value, it returns the last value. Raises django.utils.datastructures.MultiValueDictKeyError if the key does not exist. (This is a subclass of Python's standard KeyError, so you can stick to catching KeyError.)

Whereas if you perform a request.data.get('key'), it will call the.get(..)` function, and we see in the documentantation:

QueryDict.get(key, default=None)

Uses the same logic as __getitem__(), with a hook for returning a default value if the key doesn't exist.

So it means that if the key does not exists, .get(..) will return None, in case you did not provide a default, or it will return the given default if you query with request.data.get('key', somedefault).

Typically the latter is used in case the value is optional, and you want to reduce the amount of code to check if the key exists.

Willem Van Onsem
  • 443,496
  • 30
  • 428
  • 555
2

Yes both of them will give you the same results, but what makes them different is the way they retrieve the data for a given key. For this you need to understand how dictionaries in python works, lets define a dict:

>>> kwarg = {'name': 'John'}
>>> kwarg['name']
'John'
>>> kwarg['age']
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
KeyError: 'age'
>>>
>>> kwarg.get('age', 25)
25

In the above example in the first method the key has to be present whereas in second case I can define a default value if the key is not found.

Sanchit
  • 326
  • 3
  • 6