0

I have a nested tuple returned from a MySQL cursor.fetchall() containing some results in the form (datetime.date, float). I need to separate these out in to a nested dictionary of the form [month/year][day of month] - so I would like to have a dictionary (say) readings which I would reference like readings['12/2011'][13] to get the reading for 13th day of the month '12/2011'. This is with a view to producing graphs showing the daily readings for multiple months overlaid.

My difficulty is that (I believe) I need to set up the first dimension of the dictionary with the unique month/year identifiers. I am currently getting a list of these via:

list(set(["%02d/%04d" % (z[0].month, z[0].year) for z in raw]))

where raw is a list of tuples returned from the database.

Now I can easily do this as a two stage process - set up the first dimenion of the dictionary then go through the data once more to set-up the second. I wondered though if there is a readable way to do both steps at once possibly with nested dictionary/list comprehensions.

I'd be graetful for any advice. Thank you.

TimGJ
  • 1,584
  • 2
  • 16
  • 32
  • Aren't you going to need to sort the months at some stage? Is there any good reason why you don't have month keys in a natural order e.g. `'2011-12'` even if you aren't going to sort them? – John Machin Feb 11 '12 at 10:11
  • Nice bit of finessing. Thank you. They are in the 'mm/yyyy' format because those are the series labels which are used on different traces on a graph, and "12/2011" is more readable (certainly to a UK audience) than an ISO formatted date. But a very good point. – TimGJ Feb 12 '12 at 17:06

1 Answers1

1

it seems difficult to do both levels in a concise oneliner, I propose you instead to use defaultdict like this:

res = defaultdict(dict)
for z in raw:
    res["%02d/%04d"%(z[0].month, z[0].year)][z[0].day] = z
ptitpoulpe
  • 684
  • 4
  • 17