Velocity Reviews > assigning values to array element

# assigning values to array element

Ben
Guest
Posts: n/a

 10-15-2003
Hi all,

This may sound easy but I'm having trouble assigning values to array
element. My problem is as follows:

m = ['Peter', 'Sam', 'Dave', 'Carl']
for o in m:
# Here first o is 'Peter'.. I want to do something like this:
Peter = 10

# if i do %s %o = 10, it gives me error...

How can I do it?

Thanks
Ben

Peter Hansen
Guest
Posts: n/a

 10-15-2003
Ben wrote:
>
> This may sound easy but I'm having trouble assigning values to array
> element. My problem is as follows:
>
> m = ['Peter', 'Sam', 'Dave', 'Carl']
> for o in m:
> # Here first o is 'Peter'.. I want to do something like this:
> Peter = 10
>
> # if i do %s %o = 10, it gives me error...
>
> How can I do it?

You seem to want to create variables with names Peter, Sam, etc.

If that's so, you should explain your problem in more detail,
because doing this dynamically is useless: after all, how do
you plan to *retrieve* those variables if you don't know in

What you are trying to do is probably better accomplished using
Python dictionary type:

# using your "m" list of names, above:
d = {}
for name in m:
d[name] = 10

# then to access things, do this:
print d['Peter']

If you need more, please explain the rationale behind the program,
rather than just examples of code that didn't work, so we'll
understand *why* you are trying to do what you are trying to do.

-Peter

Paul Rubin
Guest
Posts: n/a

 10-15-2003
http://www.velocityreviews.com/forums/(E-Mail Removed) (Ben) writes:
> This may sound easy but I'm having trouble assigning values to array
> element. My problem is as follows:
>
> m = ['Peter', 'Sam', 'Dave', 'Carl']
> for o in m:
> # Here first o is 'Peter'.. I want to do something like this:
> Peter = 10
>
> # if i do %s %o = 10, it gives me error...
>
> How can I do it?

Um, you probably really don't want to do that. See the docs about
how Python dictionaries work. Then try something like:

m = ['Peter', 'Sam', 'Dave', 'Carl']
table = {} # note these are curly braces
for o in m:
table[o] = 10

Michael Peuser
Guest
Posts: n/a

 10-15-2003

"Ben" <(E-Mail Removed)>
>
> This may sound easy but I'm having trouble assigning values to array
> element. My problem is as follows:
>
> m = ['Peter', 'Sam', 'Dave', 'Carl']
> for o in m:
> # Here first o is 'Peter'.. I want to do something like this:
> Peter = 10
>
> # if i do %s %o = 10, it gives me error...
>
> How can I do it?

I think 'old stuff' is really appropriate here:

for index in xrange(len(m)):
m[index]=10

Kindly
MichaelP