soarinblue
soarinblue

Reputation: 1687

Construct a data structure with special requirements in python

Requirements:

  1. There is a variable, for example, related_to_dict = 10
  2. Construct a key value pair data, for example, special_dict = {0 : ref_related_to_dict}
  3. When the variable of related_to_dict changed, the value of special_dict[0] also changed to the value of related_to_dict accordingly.
  4. When the value_of special_dict[0], e.g. ref_related_to_dict changed, the value of related_to_dict also changed to the value of special_dict[0] accordingly.

Is there a way to achieve this task?

Upvotes: 0

Views: 44

Answers (1)

Claudiu
Claudiu

Reputation: 229461

You need to wrap the value in some sort of container.

class Ref:
   def __init__(self, v):
        self.val = v

And then:

related_to_dict = Ref(10)
special_dict = {0: related_to_dict}

Then it works as desired:

related_to_dict.val = 40
print(special_dict[0].val) # 40

Upvotes: 1

Related Questions