简体   繁体   中英

Able to access only last element of list in Python unicode dictionary

My Python unicode dictionary looks like this:

`<QueryDict: {u'csrfmiddlewaretoken':[u'oacUfIz5q2tPtmSoqCQi7tBDn2ejpt4x9ZiFeLKeIOyB2CHvAoJqbe1cHNZJSObP'], u'Date and Events[]': [u'2000-09-09', u'bday', u'second']}>`

When I try to access the element with key 'Date and Events[]', I get only the last element of the list. Any idea why this occurs?

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.

__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[]']

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM