-1

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)

Vingtoft
  • 13,368
  • 23
  • 86
  • 135
  • How are you creating your dictionary? Do you have an empty one at first or it's contain the first field? – Mazdak Nov 25 '16 at 18:02
  • Depends on what is meant. To "refer to another dictionary key/value when assigning a key/value", yes - just create the dictionary and assign it to a variable so it can be accessed. However the value stored will be *immediately evaluated*. To have a dependent value requires more than a dictionary, such as a lambda or object intermediary, or to have a dictionary that acts like a magical unicorn. – user2864740 Nov 25 '16 at 18:02
  • 1
    Possible duplicate of [What do I do when I need a self referential dictionary?](http://stackoverflow.com/questions/3738381/what-do-i-do-when-i-need-a-self-referential-dictionary) – Henry Heath Nov 25 '16 at 18:10

2 Answers2

3

If I understand the problem correctly, you can define the first visit date prior to creating the dictionary:

from datetime import datetime, timedelta

visit1_date = datetime(2016, 11, 23)
visits = {'visit_1': {'date': visit1_date},
          'visit_2': {'date': visit1_date + timedelta(weeks=4)}}

print(visits)

To extend that a little bit further, you may have a visits factory that would dynamically create a dictionary of visits based on a start date and the number of visits (assuming the visits come every 4 weeks evenly):

from datetime import datetime, timedelta

def visit_factory(start_date, number_of_visits):
    return {'visit_%d' % (index + 1): start_date + timedelta(weeks=4 * index)
            for index in range(number_of_visits)}


visits = visit_factory(datetime(2016, 11, 23), 2)
print(visits)
alecxe
  • 462,703
  • 120
  • 1,088
  • 1,195
2

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.

jmd_dk
  • 12,125
  • 9
  • 63
  • 94