python dictionary question
All,
This is the request from the template that i get
u'subjects': [开发者_运维问答u'7', u'4', u'5', u'3', u'2', u'1']
In my views how to extract the values like 7 4 5 3 2 1
How do i extract the above sequence from
new_subjects=request.POST.get('subjects')
Thanks.
Something like the following:
try:
int_subjects = [int(x) for x in new_subjects]
except ValueError:
#There was an error parsing.
request.POST
is an instance of QueryDict which have a method named getlist that returns a list of values for the given key.
Example:
>>> new_subjects = request.POST.getlist('subjects')
>>> print new_subjects
[u'7', u'4', u'5', u'3', u'2', u'1']
See gnibbler's response for converting the list items to integers.
try:
int_subjects = map(int, new_subjects)
except ValueError:
#There was an error parsing.
Using timeit in ipython shows that map is slightly faster than the comprehension in this case
In [99]: timeit map(int,new_subjects)
100000 loops, best of 3: 7.81 µs per loop
In [100]: timeit [int(x) for x in new_subjects]
100000 loops, best of 3: 8.8 µs per loop
精彩评论