Reputation: 3332
Is it possible to make a list of dicts such a way that when I change the dicts' content, the containing list reflects it (in spite of just storing in a copy of the original dict)?
a = {1: 1, 2, 2}
b = {3: 3, 4: 4}
c = [a, b]
c
[{1: 1, 2, 2}, {3: 3, 4: 4}]
a = {1: 6, 2: 7}
c
[{1: 1, 2, 2}, {3: 3, 4: 4}]
and not
[{1: 6, 2: 7}, {3: 3, 4: 4}]
(My goal is to have a 2D table-like structure that can be navigated both horizontally and vertically, and to avoid refreshing cols and rows after each new value entered in any cell. I need pointer-like behavior)
Upvotes: 0
Views: 153
Reputation: 117380
When you do
a = {1: 6, 2: 7}
you just reassigning variable a
, so it'll point to new dict, and variable c
is not modified at all. Previous value of a
is left only as first element of c
.
So you have to either change element of c
, like:
c[0] = {1: 6, 2: 7}
or change elements of a
(but not reassign a
):
a[1], a[2] = 6, 7
or
a.update({1:6, 2:7})
Upvotes: 1
Reputation: 129507
You can update a
in-place using update()
as opposed to reassigning it:
a.clear()
a.update({1: 6, 2: 7})
(See also: clear()
)
Using your full example:
>>> a = {1: 1, 2: 2}
>>> b = {3: 3, 4: 4}
>>> c = [a, b]
>>> c
[{1: 1, 2: 2}, {3: 3, 4: 4}]
>>> a.clear()
>>> a.update({1: 6, 2: 7})
>>> c
[{1: 6, 2: 7}, {3: 3, 4: 4}] # <--
Upvotes: 2
Reputation: 308158
Instead of reassigning a
you could modify it in place.
a[1] = 6
a[2] = 7
Upvotes: 0