Entry
How to copy lists and dictionaries?
How to copy lists and dictionaries?
Jul 5th, 2000 09:59
Nathan Wallace, unknown unknown, Hans Nowak, Snippet 30, Eric Jones
"""
Packages: basic_datatypes.lists;basic_datatypes.dictionaries
"""
"""
>First I want to thank those who helped me with my previous post. Hopefully
>this one will be as quickly answered. Here's my question: What is the
>easiest way to copy a list or dictionary?
>
> For example, I would like
>
>x = [ "b", "c" ]
>y = copy(x) # y=x makes y refer to x, I want y to be a copy of x.
>y.insert(0,"a")
>
>so that x = ["b", "c"] and y = [ "a", "b", "c"]
Your code is really close. If you do a dir() on a dictionary, you'll see
some handy methods.
>>> a={}
>>> dir(a)
['clear', 'copy', 'get', 'has_key', 'items', 'keys', 'update', 'values']
DICTIONARY COPY
Provided you want to do a shallow copy, the copy method is what your looking
for:
"""
x = {'a':1,'b':2}
y = x.copy() # y=x makes y refer to x, I want y to be a copy of x.
y['a'] = 3
print x
# {'a':1,'b':2}
print y
# {'a':3,'b':2}
"""
The update method is also handy. It will update the values of one
dictionary with the values
of another dictionary copying non-existent values and replacing existing
values.
"""
x = {'a':1,'b':2}
y = {'z':26}
y.update(x) # y=x makes y refer to x, I want y to be a copy of x.
print y
# {'a':1,'b':2,'z':26}
y['a'] = 3
print x
# {'a':1,'b':2}
print y
# {'a':3,'b':2,'z':26}
"""
LIST COPY
A list copy is easily done using the slicing operator:
"""
x=[1,2,3]
y = x[:]
y[0] = 4
print x
# [1,2,3]
print y
# [4,2,3]
"""
Note that all of these approaches result in shallow copies of the objects in
the list or dictionary. If you need deep copies, use the copy module as
Greg suggested. For shallow copies, my quick test showed that the built in
copy() method for dictionaries is about 3 times as fast as using copy() from
the copy module.
"""