Serphone
Serphone

Reputation: 107

Assign value in a for loop and not reference

I have a list of strings and i'd like for each string in the list to store it in a dictionary and send it to another function. So far it looks like this:

list = ['75001', '75002', '75003']
params = {}
for elt in list:
    params['elt'] = elt
    ...
    foo(params)

But the problem is that i'm storing the reference to elt and not the value, so in my function calls i always have the last element of list:

params['elt'] = '75003'

How could i store only the value and not the reference ?

Upvotes: 0

Views: 123

Answers (4)

martineau
martineau

Reputation: 123473

I think you want something like this:

zip_codes = ['75001', '75002', '75003']
for zip_code in zip_codes:
    params = {}
    params['zip code'] = zip_code
    ...
    foo(params)

This creates a new empty dictionary each time through the loop and adds values from the list to it before calling foo() although you don't really need that unless you're sure you assign to the same keys each time through the loop. An alternative would be to move it back out of the loop and call params.clear() at the top of the loop. Of course other keys and corresponding pieces of search information could be added before calling foo() as necessary.

Upvotes: 1

Kevin
Kevin

Reputation: 76194

If you want a dict that doesn't change after you pass it to foo, you should make a copy of that dict:

params = {}
for elt in list:
    params['elt'] = elt
    ...
    foo(params.copy())

Now, further changes to params later in the loop won't affect the copy of params that you sent to foo.

This differs from Aaron Digulla's answer in that params can still be initially created outside the loop. This can be useful if params was declared far away up in the code, and you don't want to move it into the loop; or if the initial instantiation was expensive and you don't want to do it more than once.

Upvotes: 2

Borgleader
Borgleader

Reputation: 15916

list = ['75001', '75002', '75003']
params = {}
for elt in list:
    params[elt] = elt
    ...
    foo(params)

Just remove the quotes around elt in params['elt']. What you're currently doing is repeatedly changing the value for the key 'elt'.

If you want a new dictionary each time however you can do this:

list = ['75001', '75002', '75003']
for elt in list:
    foo({'elt': elt})

Upvotes: 2

Aaron Digulla
Aaron Digulla

Reputation: 328614

The problem is that all functions get the same dictionary. Try this instead:

list = ['75001', '75002', '75003']
for elt in list:
    params = {}
    params['elt'] = elt
    ...
    foo(params)

Now each call to foo() gets a new container and they can't see each other anymore.

Upvotes: 2

Related Questions