开发者

python confusion: dict.pop

开发者 https://www.devze.com 2023-01-12 00:52 出处:网络
I am really confused as to why Python acts in a particular way. Here is an example: I have a dictionary called \"copy\". (It is a copy of an HttpRequest.POST in django.)

I am really confused as to why Python acts in a particular way.

Here is an example: I have a dictionary called "copy". (It is a copy of an HttpRequest.POST in django.)

Here is a debug session (with added line numbers):

1 (Pdb) copy
2 <QueryDict: {u'text': [u'test'], u'otherId': [u'60002'], u'cmd': [u'cA'], u'id':
3  [u'15']}>
4 (Pdb) copy['text']
5  u'test'
6 (Pdb) copy.pop('text')
7  [u'test']

My problem is that in the dictionary it looks like the values are all lists (they come from django that way.) When I access an element as in line 4 I get it as a value rather than a list, but when I access it with pop I get it as a list again.

I am really confused by that. Can a开发者_JAVA百科nyone help?


Have a look at the docs for QueryDicts. The short answer that it is a subclass of dict that modifies the way you get items, so that copy['text'] will return the last value in the list of values associated with 'text'. Since they haven't overridden pop, it will return the entire list.

You can use .getlist to get the list associated with a particular value:

copy['text']
>>> u'test'

copy.getlist('text')
>>> [u'test']

The reason for this is that some HTML elements will return multiple values for a single key.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号