tags:

views:

123

answers:

4

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.

+5  A: 

Something like the following:

try:
    int_subjects = [int(x) for x in new_subjects]
except ValueError:
    #There was an error parsing.
Kyle Butt
You shouldn't use a bare `except` clause.
Alok
Just had to fix it.
S.Lott
I didn't remember at the time what the right error was. I figured it was either googleable or someone here would know.
Kyle Butt
@Kyle Butt: It's easy. Run Python. Type `int("hi mom")` and you'll know. That's what I did. I don't rely on memory -- Gin has destroyed what little I had.
S.Lott
+3  A: 
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
gnibbler
+1 for trying to optimizing another answer (and doing so successfully)
AJ
+4  A: 

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.

drmegahertz
A: 

let's see: list comprehension, map...

...the generator version is missing:

In [3]: %timeit (int(x) for x in new_subjects)
1000000 loops, best of 3: 875 ns per loop

In [4]: %timeit map(int,new_subjects)
100000 loops, best of 3: 4.7 us per loop

benchmarking it like this is cheating though

Till Backhaus
complete nonsense
SilentGhost