Vingtoft Vingtoft - 12 days ago 8
Python Question

Python: How to make a dict field relative to another dict field

I have a dict looking like this:

visits = {'visit_1': {'date': '23-11-2016'},
'visit_2': {'date': '23-12-2016'}}


The dict consists of a lot of visits, where the 'date' is relative to the visit_1 date.

Question: Is it possible for a python dict to refer to self? Something like this:

from datetime import datetime, timedelta

visits = {'visit_1': {'date': datetime('23-11-2016')},
'visit_2': {'date': <reference_to_self>['visit_1']['date'] + timedelta(weeks=4)}


EDIT:

The first visit is not known at initialization. The dict defines a fairly complicated visit sequence (used in treatment of cancer patients)

Answer

Python containers (e.g. dictionaries) can definately refer to them selves. The problem with your example is that you are not just storing a reference, but the result of an expression (which involves the reference). This result will not itself keep any reference to how it was made, and so you loose the reference.

Another Small problem is that you cannot create an object and reference it in the same expression. Since dicts are mutable though, you can just create some of its elements first, and then add elements to it in further expression, referencing the dict via its variable name.