[Django]-Able to access only last element of list in Python unicode dictionary

2👍

__getitem__() in Dict returns the item as it is. Be it an int, float, string or list. But it’s not the case with QueryDict. Either you have to use QueryDict.getlist(key) or convert it to a Dict to get your work done. Let us assume that ‘qd’ is the QueryDict from which you want to extract the items.

    date = QueryDict.getlist('Date')
    events = QueryDict.getlist('Events[]')

If you wish to convert the QueryDict to dict, then you could do something like this to accomplish your task.

    myDict = dict(qd.iterlists())
    date = myDict['Date']
    events = myDict['Events[]']

2👍

Use .getlist(key):

>>> qd = QueryDict('a=1&a=2')            # a simple QueryDict
>>> qd
<QueryDict: {'a': ['1', '2']}>
>>> qd['a']                              # example of the problem (last item only)
'2'
>>> qd.get('a')                          # problem not solved by .get()
'2'
>>> qd.getlist('a')                      # getlist() solves it!
['1', '2']

Details:

Your dictionary is of type django.http.QueryDict which “is a dictionary-like class customized to deal with multiple values for the same key.” Unfortunately, QueryDict.__getitem__() “returns the last value” only. That means that calls to someQueryDict[key] won’t return a list, even when there are multiple values associated with the key.

The solution is to use QueryDict.getlist(key, default=None):

Returns the data with the requested key, as a Python list. Returns an
empty list if the key doesn’t exist and no default value was provided.
It’s guaranteed to return a list of some sort unless the default value
provided is not a list.

Leave a comment