0

Suppose we have a dictionary:

some_dict = {
    "first": 11111,
    "second": {
        "second_1": 22222,
        "second_2": 232323,
        "second_3": 99999
    }
}

if I create a new variable a with value some_dict["second"], then it will be a reference:

ref = some_dict["second"]

Accordingly, if I change the value of the nested dictionary second in some_dict, then it will also change in ref:

some_dict["second"]["second_1"] = "not a second_1"
print(ref)

Output:

{'second_1': 'not a second_1', 'second_2': 232323, 'second_3': 99999}

How can I create the same reference, but not to a nested dictionary, but to a value, such as int or str?

Like this:

ref = some_dict["second"]["second_1"]

some_dict["second"]["second_1"] = "not a second_1"
print(ref)

Estimated output:

not a second_1
  • 3
    It's not possible. Python has references to containers, but not to values. – Barmar Jun 18 '22 at 21:22
  • "How can I create the same reference, but not to a nested dictionary, but to a value, such as int or str?" In the same way. It just doesn't help you write the code that you want. `ref = some_dict["second"]["second_1"]` creates a "reference" to the integer. But `some_dict["second"]["second_1"] =` modifies the inner dict; it **does not modify** the integer. You cannot, in fact, modify that integer, as there are no methods that do so. Assignment never modifies the pre-existing assigned value (if any). – Karl Knechtel Jun 18 '22 at 21:26
  • Please also see https://nedbatchelder.com/text/names1.html. – Karl Knechtel Jun 18 '22 at 21:27

1 Answers1

0

The quick-and-dirty answer is to put it into a one-element list.

my_original_int = [0]
my_ref_to_int = my_original_int

Now modifications to (the integer value inside) either variable will reflect in the other.

But, that's horrible coding practice. At minimum, that should be encapsulated into a class.

class Cell:
  def __init__(self, value):
    self.value = value

my_original_int = Cell(0)
my_ref_to_int = my_original_int

Then either can be accessed or modified through the .value member.

Even better would be to make a specific class to your use case. Ask yourself why you're wanting to alias integers. "My integer represents data in a JSON file somewhere" is a great answer, and it suggests that there should be a MyJsonData class somewhere that has integer fields, and you should be passing around references to that instead of to the integers.

Basically, make your data usage as explicit as possible, and your code will be more readable and intuitive. I even go so far as to try to avoid aliasing lists and dictionaries. If I find myself needing such behavior, it's often about time for me to encapsulate that list in a class with a more specific name and detailed docstring.

Silvio Mayolo
  • 62,821
  • 6
  • 74
  • 116