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

2024-10-03 11:22:27 发布

您现在位置:Python中文网/ 问答频道 /正文

我的Python unicode字典如下所示:

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

当我试图访问键为'dateandevents[]的元素时,我只得到列表的最后一个元素。知道为什么会这样吗?在


Tags: and元素列表date字典unicodeeventssecond
2条回答

Dict中的\uuGetItem_Uu(),返回该项的原样。可以是int、float、string或list。但QueryDict不是这样。要么你必须使用查询dict.getlist(key)或者把它转换成Dict来完成你的工作。假设'qd'是您想要从中提取项目的QueryDict。在

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

如果您希望将QueryDict转换为dict,那么您可以执行以下操作来完成您的任务。在

^{pr2}$

使用.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']

详细信息:

您的字典属于^{}类型,它“是一个类似字典的类,可以处理同一个键的多个值。”不幸的是,^{}“只返回最后一个值”。这意味着对someQueryDict[key]的调用不会返回列表,即使有多个值与键关联。在

解决方案是使用^{}

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.

相关问题 更多 >