6

Is there any way to keep in a dict values references to elements of a list, and modify the list via the dict?

a = [1, 2]
b = [11, 22]

d = {k: v for k, v in zip(a, b)}
d[1] = 33
print b, d

The output is of the 2nd print:

[11, 22] {1: 33, 2: 22}

While I would like:

[33, 22] {1: 33, 2: 22}

I suspect both the dictionary creator and the modification are not correct...

In C it would be possible to keep the pointers in the dictionary and modify the value via the * operator.

Anything similar in python or any other pythonic way to achieve this?

Remi Guan
  • 21,506
  • 17
  • 64
  • 87
John Smith
  • 1,077
  • 6
  • 21
  • you are creating a iterable with `zip`. so it does not point to the same value. – sobolevn Oct 28 '15 at 10:18
  • 2
    You can't do that in Python - the dictionary and list contain references to the same immutable integer at first, but if you change the number via either reference you get a new object. – jonrsharpe Oct 28 '15 at 10:18
  • Do you really need both the list and the dictionary all the time? If not, you could just create them when needed. Otherwise, one solution would be to write a class that implements the updating behaviour, but allows access to both the list and the dictionary. – causa prima Oct 28 '15 at 10:21
  • You're searching way to pass immutable type by reference, but as noted you can't do it in Python. Only way I see is to change integers to some mutable type object. Here's example: http://pastebin.com/2YgGy2ab But better way would be find another solution. – Mikhail Gerasimov Oct 28 '15 at 10:27

0 Answers0