3

How to avoid the following while using dictionaries

a={'b':1}
c=a
c.update({'b':2})
print a # {'b':2}
print c # {'b':2}
Wayne Werner
  • 49,299
  • 29
  • 200
  • 290
Rajeev
  • 44,985
  • 76
  • 186
  • 285
  • Here 'a' and 'b' are pointing to the same memory location.Hence a change in 'a' reflects in 'b'. print(id(a),id(b)) and see that both have the same id. – Manjunath Feb 24 '14 at 12:23

4 Answers4

7

By using the dictionary copy-method. Like so:

>>> a = {'b': 1}
>>> c = a.copy()
>>> c.update({'b': 2})
>>> print a
{'b': 1}
>>> print c
{'b': 2}
>>> 

Please note that this is a shallow copy. Thus, if you have mutable objects (dictionaries, lists, etc) in your dictionary, it will copy a reference to those objects. In such cases you should use copy.deepcopy. Example below:

>>> import copy
>>> a = {'b': {'g': 4}}
>>> c = copy.deepcopy(a)
>>> c['b'].update({'g': 15})
>>> print a
{'b': {'g': 4}}
>>> print c
{'b': {'g': 15}}
msvalkon
  • 11,887
  • 2
  • 42
  • 38
2

Obviously your question has been answered. But what might help here is to correct your mental model.

In Python, variables don't store values, they name values. Check out this article for the example of the statue pointing at the hotel.

A quick and easy way to check if you're referencing the same object is to print the ID of the variable:

>>> a = {}
>>> b = a
>>> print(id(a), id(b))
12345 12345
Wayne Werner
  • 49,299
  • 29
  • 200
  • 290
0

Try to:

c = a.copy()

Also see this one: Deep copy of a dict in python

It allows you to copy by value lists inside of your dict

Community
  • 1
  • 1
Andrii Rusanov
  • 4,405
  • 2
  • 34
  • 54
0

Both variables a and c reference the same dict object, so when you mutate it through the variable c then the underlying dict object is changed. As a points to the same object, those changes will be visible from there too.

If you want to have both a and c reference a dictionary which are independent of each other, then you need to copy the dictionary, so that you actually receive two separate objects. You can do that by using dict.copy:

a = {'b': 1}
c = a.copy()
c.update({'b': 2})

print a # {'b': 1}
print c # {'b': 2}

Note that this will only create a shallow copy, so if the dictionary contains mutable objects—like another dictionary, a list or some other object—then you all copies will again reference the same underlying objects (just like your original code). If you want to avoid that, you can create a deep copy of the dictionary:

import copy
a = {'b': {'c': 1}}
b = copy.deepcopy(a)
b['b'].update({'c': 2})

print a # {'b': {'c': 1}}
print b # {'b': {'c': 2}}
Community
  • 1
  • 1
poke
  • 369,085
  • 72
  • 557
  • 602
  • I have some thing like a={'b':'{"g": 4}'} In this case can i use only .copy() – Rajeev Feb 24 '14 at 12:19
  • As mentioned, if you store mutable objects like another dictionary, you will need to create a deep copy. – poke Feb 24 '14 at 12:21