Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python: Appending a dictionary to a list - I see a pointer like behavior

I tried the following in the python interpreter:

>>> >>> a = [] >>> b = {1:'one'} >>> a.append(b) >>> a [{1: 'one'}] >>> b[1] = 'ONE' >>> a [{1: 'ONE'}] >>> 

Here, after appending the dictionary 'b' to the list 'a', I'm changing the value corresponding to the key 1 in dictionary 'a'. Somehow this change gets reflected in the list too. When I append a dictionary to a list, am I not just appending the value of dictionary? It looks as if I have appended a pointer to the dictionary to the list and hence the changes to the dictionary are getting reflected in the list too.

I do not want the change to get reflected in the list. How do I do it?

Thank you for your time!

like image 365
neo29 Avatar asked Mar 09 '11 11:03

neo29


People also ask

Can you append a dictionary to a list in Python?

Appending a dictionary to a list with the same key and different values. Using append() method. Using copy() method to list using append() method. Using deepcopy() method to list using append() method.

Why does Python think my dictionary is a list?

A dictionary is like a list, but more general. In a list, the indices have to be integers; in a dictionary they can be (almost) any type. You can think of a dictionary as a mapping between a set of indices (which are called keys) and a set of values.

Does dictionary follow indexing in Python?

The Python Dictionary object provides a key:value indexing facility. Note that dictionaries are unordered - since the values in the dictionary are indexed by keys, they are not held in any particular order, unlike a list, where each item can be located by its position in the list.


2 Answers

You are correct in that your list contains a reference to the original dictionary.

a.append(b.copy()) should do the trick.

Bear in mind that this makes a shallow copy. An alternative is to use copy.deepcopy(b), which makes a deep copy.

like image 164
NPE Avatar answered Oct 07 '22 10:10

NPE


Also with dict

a = [] b = {1:'one'}  a.append(dict(b)) print a b[1]='iuqsdgf' print a 

result

[{1: 'one'}] [{1: 'one'}] 
like image 34
eyquem Avatar answered Oct 07 '22 11:10

eyquem