0

I use this code to form a dictionary:

tt_data[dt] = {}
for hour in range(work_begins, work_ends, 2):
    tt_data[dt][hour] = ''
    if Rehearsal.objects.filter(dt__year=dt.year, dt__month=dt.month, dt__day=dt.day, dt__hour=hour).exists():
        tt_data[dt][hour] = Rehearsal.objects.get(dt__year=dt.year, dt__month=dt.month,
                                                  dt__day=dt.day, dt__hour=hour)

The strange thing is when "work_begins" equals 14, this element goes to the end of the dict:

enter image description here

Any help appreciated.

Omkommersind
  • 276
  • 5
  • 13
  • 3
    `tt_data`'s values are regular dictionaries, not ordered dictionaries, right? Regular dictionaries are unordered. – Wander Nauta Dec 20 '15 at 12:30
  • 1
    The keys in your OrderedDict are the dates. The second line of your screen capture is cut off, but it shows a list of 2-element tuples. The first element is the key, which is a date object, the second element is a value, which is a dict. Those key/dates are the things that are kept in order--not the values/dicts associated with those keys. If you want the values/dicts to be kept in order, then they have to be created as OrderedDicts. – 7stud Dec 20 '15 at 12:49
  • 1
    It's right there: `tt_data[dt] = {}` Why would you think that `{}` creates an OrderedDict? The line: `tt_data[dt][hour] = ...` inserts entries into `{}`. – 7stud Dec 20 '15 at 12:52

2 Answers2

0

Thanks, this simple edit solves the problem:

-        tt_data[dt] = {}
+        tt_data[dt] = OrderedDict()
Omkommersind
  • 276
  • 5
  • 13
-1

As stated in a couple of the comments, tt_data[dt] is a standard python dictionary, which is unordered. (See https://docs.python.org/3.5/tutorial/datastructures.html#dictionaries) for more details.

Therefore, although it looks like in other datetime examples that there is an order to the values, this is not guaranteed.

A few people have also discussed the outer OrderedDict (tt_data) that will be kept in order. This is only true in the sense that it will be kept in the order that it is created, not in any kind of sorted order. For instance if you add 20/11/2015 and then add 19/11/2015 it will not re-order them according to the dates.

Gavin
  • 1,070
  • 18
  • 24