简体   繁体   English

只能访问Python unicode字典中列表的最后一个元素

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

My Python unicode dictionary looks like this: 我的Python unicode字典看起来像这样:

`<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. 当我尝试使用键'Date and Events []'访问元素时,我只获得列表的最后一个元素。 Any idea why this occurs? 知道为什么会这样吗?

Use .getlist(key) : 使用.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." 你的字典是django.http.QueryDict类型,它是“一个类似字典的类,用于处理同一个键的多个值。” Unfortunately, QueryDict.__getitem__() "returns the last value" only. 不幸的是, QueryDict.__getitem__() “仅返回最后一个值”。 That means that calls to someQueryDict[key] won't return a list, even when there are multiple values associated with the key. 这意味着对someQueryDict[key]调用将不会返回列表,即使存在与该键相关联的多个值也是如此。

The solution is to use QueryDict.getlist(key, default=None) : 解决方案是使用QueryDict.getlist(key, default=None)

Returns the data with the requested key, as a Python list . 以Python列表的形式返回带有请求键的数据。 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. Dict中的__getitem __()按原样返回项目。 Be it an int, float, string or list. 无论是int,float,string还是list。 But it's not the case with QueryDict. 但是QueryDict的情况并非如此。 Either you have to use QueryDict.getlist(key) or convert it to a Dict to get your work done. 您必须使用QueryDict.getlist(key)或将其转换为Dict才能完成工作。 Let us assume that 'qd' is the QueryDict from which you want to extract the items. 我们假设'qd'是您要从中提取项目的QueryDict。

    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. 如果您希望将QueryDict转换为dict,那么您可以执行类似的操作来完成任务。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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