0

To the point, i got two events:

a = {'key': 'a', 'time': datetime.datetime(2020, 2, 15, 11, 18, 18, 982000)}

b = {'key': 'b', 'time': datetime.datetime(2020, 2, 1, 11, 47, 14, 522000)}

my goal is to assign and nest one event to the other like this:

a['key2'] = b

and this is result:

{'key': 'a', 'time': datetime.datetime(2020, 2, 15, 11, 18, 18, 982000), 'key2': {'key': 'b', 'time': datetime.datetime(2020, 2, 1, 11, 47, 14, 522000)}}

but when i want to assign new key to nested it works but it does also modify variable b, result:

a['key2']['nestedkey'] = {'somekey': 'somevalue'}

{'key': 'a', 'time': datetime.datetime(2020, 2, 15, 11, 18, 18, 982000), 'key2': {'key': 'b', 'time': datetime.datetime(2020, 2, 1, 11, 47, 14, 522000), 'nestedkey': {'somekey': 'somevalue'}}}

{'key': 'b', 'time': datetime.datetime(2020, 2, 1, 11, 47, 14, 522000), 'nestedkey': {'somekey': 'somevalue'}}

Can someone explain why variable b is getting modified? And if there is anyway to do it without modifying it?

poohateq
  • 25
  • 2
  • `a['key2']` refers to the *same* dictionary as `b`, so when you change one, you are changing the other. – mkrieger1 Feb 21 '20 at 16:45

2 Answers2

2

In python by default you're not making a copy of an object when you assign it. So when you're doing a['key2'] = b, a['key2] just hold a reference to b. Weather you modify b or a['key2'] it's going to modify the same object.

To make a copy you can use deepcopy:

import copy

a['key2'] = copy.deepcopy(b)

Then it would works as you are expecting, modifying a['key2'] will not modify b

Noé
  • 498
  • 3
  • 14
1

This happens because of variable b is being used by reference. Basically a['key2']=b says that a['key2'] points to the location in memory where b is stored, so when changes are made to a['key2'] or the variable b the same data is being changed.

To avoid this you can make a deep copy of of b and assign that to a[key2] like so:

import copy

a[key2] = copy.deepcopy(b)

This should give you your desired results.

To get more details about how copy works see here

Kikanye
  • 1,198
  • 1
  • 14
  • 33